What is the :argument syntax about?

O

Omar Campos

Hi all,

I've noticed that for some methods in some gems, it's necesarry to pass
arguments like this:

method( :arg1 => value, :arg2 => value, :arg3,...)

I use the syntax the same way in the examples and it works, but I'd
like to know what Ruby's doing under there. What is the : and the =>
for anyway? Thanks for any info.
 
F

Florian Gilcher

Hi all,

I've noticed that for some methods in some gems, it's necesarry to
pass
arguments like this:

method( :arg1 => value, :arg2 => value, :arg3,...)

I use the syntax the same way in the examples and it works, but I'd
like to know what Ruby's doing under there. What is the : and the =>
for anyway? Thanks for any info.

It is the same as:

method( {:arg1 => value, :arg2 => value} )

{a => b} is a Hash in Ruby, :something is a Symbol. You can read about
those everywhere, I will not write yet another introduction.
Because the parser can easily see that it is a Hash, you can omit the
{}.

On the other side, it will look like this:

def method(options = {})
arg1 = options[:arg1]
arg2 = options[:arg2]
end

It looks a bit like named arguments and has the same benefits: you can
reorder them as you like, you immediately know the meaning from the
argument list and you can omit optional arguments in a nice fashion.

Regards,
Florian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,182
Latest member
BettinaPol

Latest Threads

Top