Is there any difference between the `:key = value` and `key: value` hash notations?
Yes, there is a difference. These are legal:
h = { :$in => array }
h = { :'a.b' => 'c' }
h[:s] = 42
but these are not:
h = { $in: array }
h = { 'a.b': 'c' } # but this is okay in Ruby2.2+
h[s:] = 42
You can also use anything as a key with =>
so you can do this:
h = { C.new => 11 }
h = { 23 => 'pancakes house?' }
but you can't do this:
h = { C.new: 11 }
h = { 23: 'pancakes house?' }
The JavaScript style (key: value
) is only useful if all of your Hash keys are "simple" symbols (more or less something that matches /\A[a-z_]\w*\z/i
, AFAIK the parser uses its label pattern for these keys).
The :$in
style symbols show up a fair bit when using MongoDB so you'll end up mixing Hash styles if you use MongoDB. And, if you ever work with specific keys of Hashes (h[:k]
) rather than just whole hashes (h = { ... }
), you'll still have to use the colon-first style for symbols; you'll also have to use the leading-colon style for symbols that you use outside of Hashes. I prefer to be consistent so I don't bother with the JavaScript style at all.
Some of the problems with the JavaScript-style have been fixed in Ruby 2.2. You can now use quotes if you have symbols that aren't valid labels, for example:
h = { 'where is': 'pancakes house?', '$set': { a: 11 } }
But you still need the hashrocket if your keys are not symbols.
What's the difference between a hash with = and :
{ some_arbitrary_expression(some_argument, arg2) => another_arbitrary_expression(arg) }
Is the general syntax for Hash
literals. Any object that responds to hash
and eql?
can be used as a key in a Hash
.
{ some_valid_symbol: arbitrary_expression(arg1, arg2) }
Is the "new-style" Hash
literal syntax for Symbol
keys.
I always thought
=>
is the old syntax for:
but there seems to be really a difference.
I'm not sure where you were taught this, but I sure would like to know so I can warn others about this source. It has never been true, there are no current plans to make it true, and it probably never will be true. To my knowledge, there is nothing in the official documentation, in the RubySpec, or in any of the well-known books (The Ruby Programming Language, Programming Ruby) that says it either.
Can you please explain the difference and tell me how I can convert such an hash:
{ 'username': 'John' }
to this{ 'username' = > 'John'}
presentation?
You can change the String
representation of a Hash
by monkey-patching Hash#to_s
or Hash#inspect
, but it is unclear what that would buy you.
If a method you are using expects a Hash
whose keys are String
s and you pass it a Hash
whose keys are Symbol
s, then changing the String
representation of the Hash
is not going to help you. You need to fix the source and make sure that your keys are String
s.
Ruby syntax with hash keys and symbols
The notation introduced in Ruby 1.9 is just a shortcut, and you can see what it means using irb
:
h = { dependent: :destroy }
# => { :dependent => :destroy }
They're both symbols. Don't forget that a hash can be keyed by any object, not necessarily a symbol or a string. This is completely different from most languages where the key will be coerced into something consistent.
Using that example you can see what the types of the keys and values are:
h.keys
# => [:dependent]
h.values
# => [:destroy]
They're all symbols in this case.
What's the difference between :foo = :bar and foo: :bar?
Most of the time there's no difference, if you're running a version of Ruby (v.1.9+) that supports the foo: :bar
notation.
The advantages/disadvantages are mostly programmer preferences, except for complex keys we could often use :"foo bar"
, but that isn't supported for the newer syntax:
ash = {:'foo foo' => 1}
=> {:"foo foo"=>1}
irb(main):002:0> hash = {'foo foo': 1}
SyntaxError: (irb):2: syntax error, unexpected ':', expecting =>
Otherwise, you can use whichever feels better to you. I'd recommend that you don't mix them up though, as that becomes a readability, then a maintenance, issue.
At work I prefer to see =>
because it's a more visible delimiter for key/value pairs, which then also allows us to run the code on more versions of Ruby, if that was necessary.
What's the difference between colon : and fat arrow =
The syntax is for defining Hash key/value pairs, and the difference depends on the Ruby version.
Supported in both Ruby 1.8 and Ruby 1.9
:foo => true
Supported only in Ruby 1.9
foo: true
If you're developing in Ruby 1.9 you should probably use the syntax:
foo: true
as it appears to be the direction the community is moving in.
What is the difference between :to and = in rails
In context of Rails routes:
- Is there a difference between these two statements?
There is no difference.
- If so why is one better than the other?
No, it's the same.
- Why is the rails community switching to the ":" notation (or are
they)?
Just a more readable, 'from' => 'to'
and 'from', to: 'to'
- Moving forward with rails 4 and soon 5, are both formats still
acceptable?
Yes.
The =>
notation it's a hash ruby feature, and related to the :symbol
.
You can write symbols by two ways :key => value
and key: value
.
What are the benefits of the new hash syntax in Ruby 1.9?
It just looks nicer--it's syntactic sugar; it ends up being the same thing.
When mixing keys (ew, why would you do that?) I use the old hash-rocket syntax for the entire hash.
With symbol values I also use the old hash-rocket syntax for the entire hash–this looks icky:
{ ohai: :kthxbye }
I don't like mixing the two styles in the same hash–I think it's confusing.
This is all based on personal preference, though.
Ruby: Creating a hash key and value from a variable in Ruby
If you want to populate a new hash with certain values, you can pass them to Hash::[]
:
Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200}
Hash[ [ ["a", 100], ["b", 200] ] ] #=> {"a"=>100, "b"=>200}
Hash["a" => 100, "b" => 200] #=> {"a"=>100, "b"=>200}
So in your case:
Hash[id, 'foo']
Hash[[[id, 'foo']]]
Hash[id => 'foo']
The last syntax id => 'foo'
can also be used with {}
:
{ id => 'foo' }
Otherwise, if the hash already exists, use Hash#=[]
:
h = {}
h[id] = 'foo'
Ruby: colon before vs after
You are welcome for both, while creating Hash
:
{:name => "foo"}
#or
{name: 'foo'} # This is allowed since Ruby 1.9
But basically :name
is a Symbol
object in Ruby.
From docs
Hashes allow an alternate syntax form when your keys are always symbols. Instead of
options = { :font_size => 10, :font_family => "Arial" }
You could write it as:
options = { font_size: 10, font_family: "Arial" }
Related Topics
Ssl Error When Installing Rubygems, Unable to Pull Data from 'Https://Rubygems.Org/
Difference Between Include and Extend in Ruby
How to Get Source Code of a Method Dynamically and Also Which File Is This Method Locate In
Ruby Style: How to Check Whether a Nested Hash Element Exists
Rails Sessions Current Practices
"Bin/Rails: No Such File or Directory" W/ Ruby 2 & Rails 4 on Heroku
How to Remove Leading Whitespace Chars from Ruby Heredoc
How to Change My Ruby Version Using Rvm
Difference Between "And" and && in Ruby
What Is the Best Method of Handling Currency/Money
Pg::Error: Select Distinct, Order by Expressions Must Appear in Select List
Reducing N+1 Queries Using the Bullet and Rspec Gems
Difference Between Ruby 1.8 and Ruby 1.9