Mo.
Mo.

Reputation: 42573

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.

Upvotes: 10

Views: 2018

Answers (2)

Matt Briggs
Matt Briggs

Reputation: 42238

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.

Upvotes: 20

Nikita Rybak
Nikita Rybak

Reputation: 68016

Wow, a that's a lot of different concepts together.

1) = is plain old assignment.

a = 4;
puts a

2) => is used to declare hashes

hash = {'a' => 1, 'b' => 2, 'c' => 3}
puts hash['b'] # prints 2

3) @var lets you access object instance variable.

class MyObject
    def set_x(x)
        @x = x
    end
    def get_x
        @x
    end
end

o = MyObject.new
o.set_x 3
puts o.get_x # prints 3

4) @@var lets you access class ('static') variables.

class MyObject
    def set_x(x)
        @@x = x # now you can access '@@x' from other MyObject instance
    end
    def get_x
        @@x
    end
end

o1 = MyObject.new
o1.set_x 3
o2 = MyObject.new
puts o2.get_x  # prints 3, even though 'set_x' was invoked on different object

5) I usually think of :var as special 'label' class. Example 2 can be rephrased like this

hash = {:a => 1, :b => 2, :c => 3}
puts hash[:b] # prints 2

Upvotes: 15

Related Questions