-1

I'm trying to get this foo function to output "first" and then "second" but instead it is outputting {:x=>"first", :y=>"second"} and "this is y".

How can I use the hash as named arguments?

def foo(x='hi', y='this is y')
  puts x
  puts y
end

hash = {x: 'first', y: 'second'}
foo(**hash)
knut
  • 27,320
  • 6
  • 84
  • 112
Some Guy
  • 12,768
  • 22
  • 58
  • 86
  • Your question is very unclear. There is no such thing as "named arguments" in Ruby. Are you talking about *keyword arguments*? But there are no keyword arguments in your code. – Jörg W Mittag May 16 '19 at 04:44
  • @JörgWMittag Can you take a look at meta: https://meta.stackoverflow.com/questions/385075/shall-we-synonymize-named-parameters-and-keyword-arguments ? I think your input would be valuable there. – knut May 16 '19 at 07:17

1 Answers1

4

Just call the method with the hash: foo(hash)

The bigger problem: You didn't use named parameters (or better keyword arguments) but parameters with default values. To use named parameters you must not not use = but :.

def foo(x: 'hi', y:'this is y')
  puts x
  puts y
end

hash = {x: 'first', y: 'second'}
foo(hash)
knut
  • 27,320
  • 6
  • 84
  • 112