Rails array sort - ruby-on-rails

I have in rails this array:
#array = [{'82'=>'1'}, {'81'=>'0'},{'32'=>'12'}]
How can I sort it to have that result? I want to have this:
#array = [{'32'=>'12'}, {'82'=>'1'},{'81'=>'0'}]
and next - how then I can get #array[0] hash key (32)
This is an array of hash where hash is {'user_id'=>'counter'}

This will sort the array by value, in descending order, in place:
array.sort! { |h1, h2| h2.values.first <=> h1.values.first }
It can also be done with sort_by! followed by reverse!.
array.sort_by! { |h| h.values } .reverse!
Then, these will get you the first value and first key, respectively:
array.first.values.first
array.first.keys.first

Just append keys.sort to the end of the array. Use #array.keys.sort

#array.sort { |x,y| x.keys.first <=> y.keys.first }

Try using Enumerable#sort_by, and Array#reverse! to change the order.
> #array.sort_by { |h| h.values.first }.reverse!
=> [{"32"=>"12"}, {"82"=>"1"}, {"81"=>"0"}]

Related

How can I get the value of the name only on this array?

This is the output array when I do
result = JSON.parse(response.body)
result.values.each {|element|
puts element
}
Result:
{"id"=>3, "code"=>"3", "name"=>"Market", "status"=>"A", "refcode"=>"001"}
{"id"=>4, "code"=>"4", "name"=>"Mall", "status"=>"A", "refcode"=>"002"}
From this array, I only want to get the name value. I tried this
puts result['data'][0]['name'] and it worked fine but I want to get all the name in the array
This is my expected output
Market
Mall
Try using Array#map and over each element, to access it's 'name' key, like:
p array.map { |element| element['name'] }
# ["Market", "Mall"]
I think it'd be something like:
result = JSON.parse(response.body)
result.values.map { |element| element['name'] }
# ["Market", "Mall"]
Since with each and puts you're only iterating and printing the hashes in the array, you could access the 'name' key from result.values.
I wont modify much. Since your name element is at position 3. access it like array because you are using values.each
result = JSON.parse(response.body)
result.values.each {|element|
puts element[2]
}

How to get each value from hash of array?

I have a hash of array with key, values in ruby which I want to pass each value with key. I want to extract content using my hash. My code is :
def get_content
GetPageContent.new(#pdf.id, session[:selected_pages][#document.id.to_s])
end
in session[:selected_pages] I got like this
{"15"=>["001"], "24"=>["001","005"]}
In this first value is pdf id and second value is page number of that pdf.
I want this :
GetPageContent.new(#pdf.id, session[:selected_pages][#document.id.to_s])
I want to pass all values like this:
GetPageContent.new(15, 001)
GetPageContent.new(24, 001)
GetPageContent.new(24, 005)
How to map each key values from hash of array?
A simple nested loop will suffice:
session[:selected_pages].each do |pdf_id, page_numbers|
page_numbers.each { |page_number| GetPageContent.new(pdf_id, page_number) }
end
You can use something like this
hsh = {"15"=>["001"], "24"=>["001","005"]}
hsh.each(&->(page, pages){pages.each{|id| GetPageContent.new(id, page)}})
You could do something like this to get a simple array. h is your hash
pages = h.flat_map { |key, arr| ([key] * arr.size).zip(arr) }
=> [["15", "001"], ["24", "001"], ["24", "005"]]
pages.map! { |pdf_id, page_number| GetPageContent.new(pdf_id, page_number) }
session[:selected_pages]
.map{|k, v| [k].product(v)}.flatten(1)
# => [["15", "001"], ["24", "001"], ["24", "005"]]
The rest is up to you.

How to sort Ruby Hash based on date?

I have a hash object with the following structure:
{"action1"=>
{"2014-08-20"=>0,
"2014-07-26"=>1,
"2014-07-31"=>1
},
"action2"=>
{"2014-08-01"=>2,
"2014-08-20"=>2,
"2014-07-25"=>2,
"2014-08-06"=>1,
"2014-08-21"=>1
}
"action3"=>
{"2014-07-30"=>2,
"2014-07-31"=>1,
"2014-07-22"=>1,
}
}
I want to sort the hash based on the date and return back a Hash(Not array). The final result should be:
{"action1"=>
{"2014-07-26"=>1,
"2014-07-31"=>1,
"2014-08-20"=>0
},
"action2"=>
{"2014-07-25"=>2,
"2014-08-01"=>2,
"2014-08-06"=>2,
"2014-08-20"=>1,
"2014-08-21"=>1
}
"action3"=>
{"2014-07-22"=>1,
"2014-07-30"=>2,
"2014-07-31"=>1
}
}
Iterate over the hash, and for each value, sort.
h = {"action1"=>
{"2014-08-20"=>0,
"2014-07-26"=>1,
"2014-07-31"=>1
},
"action2"=>
{"2014-08-01"=>2,
"2014-08-20"=>2,
"2014-07-25"=>2,
"2014-08-06"=>1,
"2014-08-21"=>1
},
"action3"=>
{"2014-07-30"=>2,
"2014-07-31"=>1,
"2014-07-22"=>1,
}
}
h.each do |k, v|
h[k] = Hash[v.sort]
end
Here you need to iterate your hash and fetch the value than you need to apply sort_by function on each value so you will get your result
hashName.each do |key, hash|
Hash[hashName.sort_by{|k,v| k}]
end
This is all you need:
h.each { |k,v| h[k] = v.sort.to_h }
#=> {"action1"=>{"2014-07-26"=>1, "2014-07-31"=>1, "2014-08-20"=>0},
# "action2"=>{"2014-07-25"=>2, "2014-08-01"=>2, "2014-08-06"=>1,
# "2014-08-20"=>2, "2014-08-21"=>1},
# "action3"=>{"2014-07-22"=>1, "2014-07-30"=>2, "2014-07-31"=>1}}
Hash#to_h appeared in Ruby 2.0. For earlier versions, use the class method Hash::[]: i.e., replace v.sort.to_h with Hash[v.sort].

Split an Array of arrays into 2 separate arrays in Ruby

I have a hash with some key value pairs as below:
#level2 = #l2.inject(Hash.new(0)) { |hash,element|
hash[element] +=1
hash }
I perform some sorting on the hash based on the keys.
#level2 = #level2.sort_by { |x, _| x }.reverse
Now I assume that the sort_by gives me an Array of Arrays. I want to split this into 2 arrays such that my first array should contain all keys and second array should contain all values.
The hash#keys and hash#values are not accessible after sorting the hash. So that does not work in this case.
Regardless of how you make the hash it will will have a Hash#keys method and a Hash#values. They both return arrays that are just what you seem to want.
keys_array = #level2.keys
values_array = #level2.values
You could iterate over the array of arrays and add each element to a new array. This would keep the order of the elements.
keys_array = []
values_array = []
#level2.each do |key, value|
keys_array << key
values_array << value
end

How do you sort an array of objects?

I have an object as follows:
[{:id=>2, :fname=>"Ron", :lname=>"XXXXX", :photo=>"XXX"}, {:id=>3, :fname=>"Dain", :lname=>"XXXX", :photo=>"XXXXXXX"}, {:id=>1, :fname=>"Bob", :lname=>"XXXXXX", :photo=>"XXXX"}]
I want to sort this by fname, alphabetically case insensitive so it would result in
id: 1,3,2
How can I sort this? I'm trying:
#people.sort! { |x,y| y[:fname] <=> x[:fname] }
But that has no effect.
You can use sort_by.
#people.sort_by! { |x| x[:fname].downcase }
(the downcase is for the case insensitivity)
For completeness, the issues with the provided code are:
the arguments are in the wrong order
downcase is not being called
The following code works using the sort method.
#people.sort! { |x,y| x[:fname].downcase <=> y[:fname].downcase }
As proof that both of these methods do the same thing:
#people.sort_by {|x| x[:fname].downcase} == #people.sort { |x,y| x[:fname].downcase <=> y[:fname].downcase }
Returns true.

Resources