Reputation: 356
I see a lot of people using keyword arguments in their Ruby code. I also see a lot of people using options hashes. When should I use keyword arguments and when should I use options hashes? This really confuses me. From what I've seen keyword arguments are much better than options hashes in many cases. For instance:
class Foo
def initialize(kwarg1: nil, kwarg2: nil)
@var1 = kwarg1 if kwarg1
@var2 = kwarg2 if kwarg2
end
end
looks much better and clearer than
class Foo
def initialize(options = {})
@var1 = options[:var1] if options[:var1]
@var2 = options[:var2] if options[:var2]
end
end
Upvotes: 5
Views: 1108
Reputation: 959
There is a rule in The Ruby Style Guide for it:
Use keyword arguments instead of option hashes.
# bad
def some_method(options = {})
bar = options.fetch(:bar, false)
puts bar
end
# good
def some_method(bar: false)
puts bar
end
It is a de facto coding standard and if you follow it you will never have a problem with your customers' reviewing of your code.
There is only one exception to this rule: if your method needs a really large number of different rarely used options that are really hard to list in the arguments list, only then it is worth using the option hash. But such situations should be avoided if possible.
Upvotes: 5