Illia  Kuzma Illia Kuzma - 2 months ago 9
Ruby Question

Best way to send() optional parameter in Rails

I have a method which accepts two parameters. One of them is optional. These params are actually names of methods which should be send to an object. How to avoid getting

NoMethodError
if the second parameter is missed without using condition? Can I send some "empty" method which doesn't do anything? In my case this works fine, but it doesn't look good. Thanks.

def foo param_1, parm_2='to_s'
object.public_send(param_1).public_send(param_2)
end


UPD
send is changed to public_send thanks to @Surya

Answer

If you're using Ruby 2.2.0 or later you can call #itself on any object and get that object. So in your example you can do

def foo param_1, param_2 = :itself
 object.send(param_1).send(param_2)
end

And it will be the same as

def foo param_1, param_2 = nil
  thing = object.send(param_1)
  if param_2
    thing.send(param_2)
  else
    thing
  end
end

I also second Surya's advice to always use #public_send instead.

Comments