Reputation: 5442
I am trying to append values in hash specific to particular key and value and then sort them based on values. So here is what I am trying to do
@arr = Hash.new
$m.each do |s|
if (s.start.hour == check.hour)
if params[:type] == 'A'
s.As.each do |w|
@arr['name'].push((w.name))
@arr['id'].push((w.id).to_i)
end
end
end
end
It is obvious that I will get only last value but I could not find out how to append these values for this hash.
Not much familiar with ruby so help appreciated on this and some idea how to sort the created hash with respect to 'id's in @arr
Links that I have already tried 1 2
Upvotes: 0
Views: 192
Reputation: 74680
For your requirements, you are using the Hash in way that makes more work later. Your current data structure will look like this:
{
id: [ 1, 2, 3 ],
name: [ a, b, c ]
}
Which means you have to use arrays and indexes to sort and line up the id
and name
.
Hash's support what you are trying to achieve out of the box if you restructure it to use the id
as a key:
{
1: { name: a },
2: { name: b },
3: { name: c }
}
To do this you can assign values to the Hash in your loop like so:
@arr[w.id.to_i] = { "name" => w.name }
Then your Hash can be accessed, in order with:
@arr.sort.map do |id, value|
# work with id and value["name"]
end
Reiterating what Mark Thomas noted, use a meaningful name for the Hash instead of @arr
as that only adds confusion.
Upvotes: 2