Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

While learning Ruby I've come across the "=>" operator on occasion. Usually I see it in the form of

:symbol => value 

and it seems to be used frequently when passing values to functions. What exactly is that operator called? What does it do/mean? Is it built into Ruby or is it something that different frameworks like Rails and DataMapper add to the symbol class? Is it only used in conjunction with the symbol class? Thanks.

like image 719
Dustin Martin Avatar asked Jan 11 '11 21:01

Dustin Martin


People also ask

How do you check if there are duplicates in an array Ruby?

select { array. count } is a nested loop, you're doing an O(n^2) complex algorithm for something which can be done in O(n). You're right, to solve this Skizit's question we can use in O(n); but in order to find out which elements are duplicated an O(n^2) algo is the only way I can think of so far.

Can a hash have duplicate keys Ruby?

Short answer is no, hashes need to have unique keys.

What does .each mean in Ruby?

each is just another method on an object. That means that if you want to iterate over an array with each , you're calling the each method on that array object. It takes a list as it's first argument and a block as the second argument.


1 Answers

=> 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.

like image 166
sepp2k Avatar answered Sep 25 '22 22:09

sepp2k