2

I just started learning ruby on rails, and I'm wondering when I should use "=>" and when I should use "=" for assignment. I am seeing that you use "=>" for hash, for assigning values to symbols in migrations, but i'm not sure where to draw the line.

Thanks!

2
  • 3
    Symbols can't be assigned to, the same way as numbers can't be assigned to. Only variables can be assigned to. Mar 16, 2013 at 8:12
  • Ruby's use of => as the "assignment" operator for hashes comes from Perl, which uses the same operator, however, => doesn't mean "assign". Instead, think of it meaning "associated with". In Perl, => is really an alias for , which ends up defining an array of the key and value pair. So, in Ruby, don't think of it as assignment either and think of it as association again. This fits nicely when you know that in other languages they call hashes "associated arrays". Mar 17, 2013 at 7:10

3 Answers 3

7

The => symbol is used solely for hashes. Ruby has a feature in which hashes can be passed as the last argument to a method call without including the surrounding braces. This provides something that resembles keyword arguments (though until Ruby 2.0, Ruby didn't have keyword arguments).

So when you see this:

t.integer :foo, :default => 5

What it really means is this:

t.integer(:foo, { :default => 5 })

The rest is just syntactic sugar designed to make it look nicer.

The = symbol, on the other hand, is the assignment operator you know and love from nearly any programming language.

0

I struggled with this for a while, but now prefer to use the new style for hashes wherever possible

t.integer :foo, default: 5
t.string :bar, default: 'Dave'
0

=> is not the same as assignment, but I can see why it is confusing. In a hash you create a key and a value as a pair. The key and value can be anything

{'key1' => 'some value', :symbol_key => 'other value'}

This is different to the assignment, which you can see clearly because if you want the above hash to remain available to your program, you either have to pass it to a method or assign it to a variable

myhash = {'key1' => 'some value', :symbol_key => 'other value'}

And only now can you retrieve stuff from your hash

puts myhash['key1']

So the => operator is actually used to construct hashes (or dictionary objects), assignment allows you to store values in the program.

What is happening quite commonly Rails (and therefore in migrations), is that the hash is being created and passed to the method call without you realising it. But the plumbing is still the same, it's still only a hash that is created.

In Ruby 1.9 you can now define hashes using a javascript-like syntax, so you might start seeing this as well.

myhash = {key1: 'some value', key2: 'other value'}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.