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!

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

I have not seen usage like first example, can you please explain what is happening in that case, especially what does a: really mean in this case.
@WandMaker these are simple hash-parameters, accepted since Ruby2, but without default values. You should’ve seen def fun a: 42, b: nil — that’s the same.
Thanks, got it now. Its called keyword arguments
@WandMaker Indeed, I can’t memoize that name for unknown reason :)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.