Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to understand specific bit of ruby syntax

I'm new to both Ruby and Rails, and as I go over various tutorials, I occasionally hit on a bit of Ruby syntax that I just can't grok.

For instance, what does this actually do?

root to: "welcome#index"

I can gather that this is probably a method named "root", but I'm lost after that. "To" isn't a symbol, is it? The colon would be before, as in ":to" if it were. Is this some form of keyword argument utilizing hashes? I can't make this syntax work when trying it in irb with ruby1.9.3.

I know this might be a RTFM question, but I can't even think of what to google for this.

Thanks!

I'm still playing around with this syntax,

def func(h)
    puts h[:to]
end

x = { :to => "welcome#index" }
y = :to => "welcome#index"
z = to: "welcome#index" 

func to: "welcome#index"

I see that this example only works with the lines defining "y" and "z" commented out. So the braceless and the "colon-after" syntax are only valid in the context of calling a method?

like image 538
zchtodd Avatar asked Jul 04 '13 19:07

zchtodd


People also ask

What syntax does Ruby use?

The syntax of the Ruby programming language is broadly similar to that of Perl and Python. Class and method definitions are signaled by keywords, whereas code blocks can be defined by either keywords or braces. In contrast to Perl, variables are not obligatorily prefixed with a sigil.

What does :+ mean in Ruby?

inject(:+) is not Symbol#to_proc, :+ has no special meaning in the ruby language - it's just a symbol.


2 Answers

First, that's right - root is a method call. Now

to: 'welcome#index' 

is equivalent to

:to => 'welcome#index'

and it's a Hash where the key is :to symbol and value is 'welcome#index' string. You can use this syntax in defining hashes since Ruby 1.9.

like image 102
Marek Lipka Avatar answered Nov 15 '22 10:11

Marek Lipka


It's equivalent to

root(:to => "welcome#index")

I'm having trouble finding the official documentation on the new hash syntax, but when you see foo: bar, it means that foo is a symbol used as a key in the hash and has a value bar.

like image 36
Mark Rushakoff Avatar answered Nov 15 '22 10:11

Mark Rushakoff