Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby multiple named arguments

I'm very new to ruby and I'm trying to write a web application using the rails framework. Through reading I've seen methods being called like this:

some_method "first argument", :other_arg => "value1", :other_arg2 => "value2"

Where you can pass an unlimited number of arguments.

How do you create a method in ruby that can be used in this way?

Thanks for the help.

like image 838
Brian DiCasa Avatar asked Nov 30 '22 19:11

Brian DiCasa


1 Answers

That works because Ruby assumes the values are a Hash if you call the method that way.

Here is how you would define one:

def my_method( value, hash = {})
  # value is requred
  # hash can really contain any number of key/value pairs
end

And you could call it like this:

my_method('nice', {:first => true, :second => false})

Or

my_method('nice', :first => true, :second => false )
like image 98
Doug Neiner Avatar answered Dec 05 '22 14:12

Doug Neiner