Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use keyword arguments and options hashes?

Tags:

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
like image 280
Noctilucente Avatar asked Jan 26 '19 02:01

Noctilucente


People also ask

When should we use keyword arguments?

Keyword arguments can often be used to make function calls more explicit. This takes a file object output_file and contents string and writes a gzipped version of the string to the output file. Notice that using this keyword argument call style made it more obvious what each of these three arguments represent.

What are the benefits of using keyword arguments?

There are two advantages - one, using the function is easier since we do not need to worry about the order of the arguments. Two, we can give values to only those parameters which we want, provided that the other parameters have default argument values.

What is keyword arguments in Ruby?

What are keyword arguments? Keyword arguments are a feature in Ruby 2.0 and higher. They're an alternative to positional arguments, and are really similar (conceptually) to passing a hash to a function, but with better and more explicit errors.

Should you use keyword arguments in python?

Use the Python keyword arguments to make your function call more readable and obvious, especially for functions that accept many arguments. All the arguments after the first keyword argument must also be keyword arguments too.


1 Answers

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.

like image 116
Ivan Olshansky Avatar answered Oct 01 '22 23:10

Ivan Olshansky