6

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
1
  • 2
    I suspect the majority of the code where you see options hashes was either written before Ruby supported keyword arguments, or was written by programmers who learned Ruby before Ruby supported keyword arguments (or learned Ruby from tutorials which were written before Ruby supported keyword arguments), or both. Or, they have certain backwards-compatibility requirements with older client code that was written before Ruby supported keyword arguments. Commented Jan 26, 2019 at 13:01

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.