4

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.

4 Answers 4

17

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 )
Sign up to request clarification or add additional context in comments.

Comments

3

This is actually just a method that has a hash as an argument, below is a code example.

def funcUsingHash(input)
    input.each { |k,v|
        puts "%s=%s" % [k, v]
    }
end

funcUsingHash :a => 1, :b => 2, :c => 3

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

Comments

1

Maybe that *args can help you?

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

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.

Comments

0

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

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

However, in Ruby 2.0.0, it is generally better to use a new feature called keyword arguments:

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

The advantages of using the new syntax instead of using a hash are:

  • It is less typing to access the optional arguments (e.g. other_arg instead of options[:other_arg]).
  • It is easy to specify a default value for the optional arguments.
  • Ruby will automatically detect if an invalid argument name was used by the caller and throw an exception.

One disadvantage of the new syntax is that you cannot (as far as I know) easily send all of the keyword arguments to some other method, because you don't have a hash object that represents them.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.