Skip to content

Instantly share code, notes, and snippets.

@oren
Created May 31, 2011 01:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oren/999737 to your computer and use it in GitHub Desktop.
Save oren/999737 to your computer and use it in GitHub Desktop.
goal:
-----
return an array of names that start with j and sorted by id
["josh", "jordan"]
arr = [{name: 'jordan',id: 3}, {name: 'josh',id: 1}, {name: 'rob',id: 5}]
1)
arr.select!{ |a| a[:name][/\Aj/] }
arr.sort!{ |a,b| a[:id] <=> b[:id] }
arr.map!{ |a| a[:name] }
2)
arr.select!{ |a| a[:name][/\Aj/] }.sort!{ |a,b| a[:id] <=> b[:id] }.map!{ |a| a[:name] }
3)
arr.sort!{ |a,b| a[:id] <=> b[:id] }
arr = arr.inject([]) do |array_so_far, current_item|
array_so_far << current_item[:name] if current_item[:name][/\Aj/]
array_so_far
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment