0

I would like to call a method in Ruby, which has an optional parameter.

I tried some ways, but none of them is working. Can you help me, how can I call this method? I never used Ruby before, so please help me refine the question itself. I tried googling the problem, but I think I use the wrong terms.

I read this: Ruby Methods and Optional parameters and this: A method with an optional parameter, but with no luck.

The method looks like this:

def method(param1, param2, options={})
    
    ...

    if options["something"]
        ...
    end

    ...

end

I tried the call, for example, like this:

method("param1", "param2", :something => true)

With my tries, the code runs but does not enter in the if condition. I would like to call this method in the way, that the codes in the if statement would be run.

SiGe
  • 341
  • 6
  • 18

2 Answers2

2

It doesn't work because you are sending symbol (:something) instead of string key ('something'). They are different objects.

Change:

method("param1", "param2", :something => true)

to

method("param1", "param2", 'something' => true)

or handle in method by if options[:something]

kiddorails
  • 12,961
  • 2
  • 32
  • 41
0

Call your method with the same param type, or if you want to be able to pass either symbol or string key you can handle that in your method.

def foo(a,b, opt={})
  if opt[:something] || opt['something']
    puts 'something'
  end
end

Now you can call this with string or symbol keys:

foo('a','b', 'something' => true )
#or 
foo('a','b', something: true )
lacostenycoder
  • 10,623
  • 4
  • 31
  • 48