Ruby multiple named arguments

I am very new to ruby ​​and I am trying to write a web application using the rails framework. Through reading, I saw methods called like this:

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

If you can pass an unlimited number of arguments.

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

Thanks for the help.

+4
source share
4 answers

This works because Ruby assumes Hash values ​​if you call the method this 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 can call it like this:

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

or

 my_method('nice', :first => true, :second => false ) 
+17
source

In fact, this is just a method with a hash as an argument, the following is an example code.

 def funcUsingHash(input) input.each { |k,v| puts "%s=%s" % [k, v] } end funcUsingHash :a => 1, :b => 2, :c => 3 

Learn more about hashes here http://www-users.math.umd.edu/~dcarrera/ruby/0.3/chp_03/hashes.html

+3
source

Maybe * args can help you?

 def meh(a, *args) puts a args.each {|x| yx} end 

The result of this method is

 irb(main):005:0> meh(1,2,3,4) 1 --- 2 --- 3 --- 4 => [2, 3, 4] 

But I prefer this method in my scripts.

+1
source

You can make the last argument an optional hash to achieve this:

 def some_method(x, options = {}) # access options[:other_arg], etc. end 

However, in Ruby 2.0.0 it is usually best to use the new keyword argument function:

 def some_method(x, other_arg: "value1", other_arg2: "value2") # access other_arg, etc. end 

Benefits of using the new syntax instead of using a hash:

  • This introduces access to optional arguments less (for example, other_arg instead of options[:other_arg] ).
  • It is easy to specify a default value for optional arguments.
  • Ruby will automatically detect that the caller used an invalid argument name and threw an exception.

One of the drawbacks of the new syntax is that you cannot (as far as I know) easily send all keyword arguments to another method because you do not have a hash object that represents them.

Fortunately, the syntax for calling these two types of methods is the same, so you can move from one to the other without breaking good code.

0
source

All Articles