1

I'll try to explain myself a little bit more

# Lets say I have this hash
options = {a: 1, b: 2}

# and here I'm calling the method
some_method(options)

def some_method(options)
  # now instead of using options[:a] I'd like to simply use a.
  options.delete_nesting_and_create_vars
  a + b # :a + :b also good.

thanks!

Ilya Libin
  • 1,576
  • 2
  • 17
  • 39
  • Possible duplicate of [How to dynamically create a local variable?](http://stackoverflow.com/questions/18552891/how-to-dynamically-create-a-local-variable) – Wand Maker Jan 27 '16 at 16:05

2 Answers2

4

Is it possible using Ruby2 splat parameters:

options = {a: 1, b: 2}

def some_method1(a:, b:)
  a + b
end

or:

def some_method2(**options)
  options[:a] + options[:b]
end


some_method1 **options
#⇒ 3
some_method2 **options
#⇒ 3
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
2

If your options are fixed, like only :a and :b are the only keys, you can write the method like this:

def some_method(a:, b:)
  a + b
end

options = {a: 1, b: 2}

some_method(options) #=> 3
Babar Al-Amin
  • 3,939
  • 1
  • 16
  • 20