Skip to content

Instantly share code, notes, and snippets.

@skoji
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skoji/9359b5f32876b8b32852 to your computer and use it in GitHub Desktop.
Save skoji/9359b5f32876b8b32852 to your computer and use it in GitHub Desktop.
デフォルト引数

rubyでメソッドの引数にデフォルト式を渡したとき、その引数が省略されたかどうか知る一番よい方法はなんだろう。

ふつうに

class TheClass
  def the_method(a = nil)
    if a.nil?
        do_something
    else
        do_something_with a
    end
  end
end

ってやると、引数が省略されたのか、nilがわたされたのか、区別がつかない。

class TheClass
   def the_method(a=(val = :marker))
     if val == :marker
        do_something
     else
         do_something_with a
     end
   end
end

ってやれば区別はつくけど、なんかトリッキーだ。

@takahashim
Copy link

基本は「引数が省略されたかどうかを知らなくて良い」設計にするのが筋ではないかと。

def the_method(*args)
  if args.empty?
    do_something
  else
    do_something_with(*args)
  end
end

みたいなのもできますが。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment