Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between "=" & "=>" and "@variable", "@@variable" and ":variable" in ruby?

I know these are the basics of rails but i still don't know the full difference between = sign and => and the difference between @some_variable, @@some_variable and :some_variable in rails.

Thanks.

like image 819
Mo. Avatar asked Aug 21 '10 19:08

Mo.


1 Answers

OK.

The difference between the = and the => operators is that the first is assignment, the second represents an association in a hash (associative array). So { :key => 'val' } is saying "create an associative array, with :key being the key, and 'val' being the value". If you want to sound like a Rubyist, we call this the "hashrocket". (Believe it or not, this isn't the most strange operator in Ruby; we also have the <=>, or "spaceship operator".)

You may be confused because there is a bit of a shortcut you can use in methods, if the last parameter is a hash, you can omit the squiggly brackets ({}). so calling render :partial => 'foo' is basically calling the render method, passing in a hash with a single key/value pair. Because of this, you often see a hash as the last parameter to sort of have a poor man's optional parameters (you see something similar done in JavaScript too).

In Ruby, any normal word is a local variable. So foo inside a method is a variable scoped to the method level. Prefixing a variable with @ means scope the variable to the instance. So @foo in a method is an instance level.

@@ means a class variable, meaning that @@ variables are in scope of the class, and all instances.

: means symbol. A symbol in Ruby is a special kind of string that implies that it will be used as a key. If you are coming from C#/Java, they are similar in use to the key part of an enum. There are some other differences too, but basically any time you are going to treat a string as any sort of key, you use a symbol instead.

like image 100
Matt Briggs Avatar answered Nov 02 '22 19:11

Matt Briggs