I'm using koala to get the following JSON object from facebook:
@friends = [{"name"=>"Jolie Chide", "gender"=>"female", "id"=>"4216323"},
{"name"=>"Seth Spring", "gender"=>"male", "id"=>"3429277"}]
What I would like to do is the following:
<% @friends.where(:gender == "female").order("@friends['name'] ASC").each do |friend| %>
<%= friend['name'] %>
<% end %>
As you know, this will not work. I'm used to standard Ruby objects and not with the JSON above. If anyone has any advice on how to get the above to work, even if it means converting the data from JSON, that would be great. Thanks for any help.
What you have there is not JSON, but an Array
of Hash
es. These are built-in Ruby collections, rather than ActiveRecord relations, and they have methods like select
and sort_by
that allow you to do the kinds of things you want to do there. You should become familiar with these classes and their methods, because they're much more basic to Ruby than the ActiveRecord stuff is, and they are used everywhere.
The operation you want can be expressed as follows:
@friends.select {|hash| hash['gender'] == 'female'}.sort_by {|hash| hash['name']}
This is the best way to grab the json data
and assign to instance variable and use following.
Ascending
@graph = @abc.sort_by { |hash| hash['created_time'] }
or
graph = abc.sort_by { |hash| hash['created_time'] }
Descending
@graph = @abc.sort_by { |hash| hash['created_time'] }.reverse!
or
graph = abc.sort_by { |hash| hash['created_time'] }.reverse!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.