In Ruby what does “=>” mean and how does it work? [duplicate]

淺唱寂寞╮ 提交于 2019-11-28 19:07:18

=> separates the keys from the values in a hashmap literal. It is not overloadable and not specifically connected to symbols.

A hashmap literal has the form {key1 => value1, key2 => value2, ...}, but when used as the last parameter of a function, you can leave off the curly braces. So when you see a function call like f(:a => 1, :b => 2), f is called with one argument, which is a hashmap that has the keys :a and :b and the values 1 and 2.

You might hear this operator referred to as a "hash rocket," meaning you use it when defining a ruby hash.

This is the Ruby Hash documentation, if you're not familiar: http://www.ruby-doc.org/core/classes/Hash.html

Note that in Ruby 1.9, if you're defining a hash that uses symbols as keys, there's now an alternative syntax available to you: http://blog.peepcode.com/tutorials/2011/rip-ruby-hash-rocket-syntax

amrnt

Tip: if you're using it in a hash like {:a => "A", :b => "B"}, in Ruby 1.9, you can use it like a JSON hash:

{
  a: "A",
  b: "B"
}

If you want to do any further Googling, => is sometimes called a hashrocket, because it looks like a rocket (in the same sense that <=> looks like a spaceship), and it's used in hashes.

Or you could use SymbolHound.

d135-1r43

In addition to In Ruby what does "=>" mean and how does it work?:

You mostly will see the => to define parameters for a function. Think of this as a nice convenience: You need not remember the right order of your parameters, as all parameters are wrapped into a giant hash. So if you have a simple helper method like

link_to "My link", my_path, :confirm => "Are you sure?"

this is way better than

link_to "My link", my_path, null, null, null, null, "Are you sure?"

just because you want to use a rarely used parameter. So passing parameters with a hash is just a convention in Ruby/Rails to make life easier.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!