What is the average * and ruby ​​smoothing

I am new to ruby ​​language, so when I tried to sort the hash by value I used this method to sort:

movie_popularity.sort_by{|m,p| p}.reverse

but the sort method returns an array, while I need a hash to return, so I used this command:

movie_popularity=Hash[*movie_popularity.sort_by{|m,p| p}.reverse.flatten]

my question is what is the meaning *and flattenin the above line?

Thanks =)

+5
source share
2 answers

*called the "splat operator"; I'm not sure I can give you a technical definition (although I’m sure that you will find it soon enough with Google), but the way I would describe it is that it basically replaces multiple letters with values ​​separated by commas in the code.

, Hash[], . Hash [], :

# Returns { "foo" => 1, "bar" => 2 }
h = Hash["foo", 1, "bar", 2]

, -, ; () . * , - , , movie_popularity.sort_by{|m,p| p}.reverse.flatten.

flatten: sort_by , Enumerable, ( Array Hash) . , , , :

hash.each { |value| ... }

:

hash.each { |key, value| ... }

, . , sort_by . flatten , :

# Returns [1, 2, 3, 4]
[[1, 2], [3, 4]].flatten
+10

'flatten' : http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-flatten

'*' - splat: http://theplana.wordpress.com/2007/03/03/ruby-idioms-the-splat-operator/

URL- :

a = [[:planes, 21], [:cars, 36]]
h = Hash[*a]  # => { :planes=>21, :cars=>36}
+2

All Articles