users_by_name = {}
users.each { |u| users_by_name[u.name] = u }
Which is of course silliness now that we know about index_by.
users_by_name = users.index_by(&:name)Slick.
writing code between lawsuit threats.
|
Showing posts with label method_of_the_day. Show all posts
Showing posts with label method_of_the_day. Show all posts
Thursday, November 20, 2008Method of the Day: index_by
Just stumbled on to this one. I can't tell you how many times I've wanted this functionality.
You have an array, but you want a hash keyed by an attribute of the items in the array. Typically, you'd do something like this:
users_by_name = {}
users.each { |u| users_by_name[u.name] = u }
Which is of course silliness now that we know about index_by.
users_by_name = users.index_by(&:name)Slick. Thursday, October 23, 2008Method of the Day: Array()
Another oldy but a goodie...
Array() wraps its parameter in an array. If it's already an array, it just returns it. If it's nil, it returns an empty array. It's super useful when you want to write a method that can take a single instance of an object or an array of objects.
Array(nil) => []
Array([]) => []
Array(1) => [1]
Array([1]) => [1]
def do_stuff(model_or_models)
models = Array(model_or_models)
models.each do |model|
# do stuff...
end
end
Wednesday, September 3, 2008Method of the Day: Array#in_groups_of
This one is great for building rows of tables.
<table>
<% @models.in_groups_of(3).each do |row| %>
<tr>
<% row.each do |model| %>
<td><%= model.to_s %></td>
<% end %>
</tr>
<% end %>
</table>
This will render the array in a left-to-right, top-down order. If you want to render in top-down, left-to-right order, try this:
<% num_cols = 3 %>
<% @models.in_groups_of((@models.length/num_cols).ceil).transpose.each do |row| %>
...
That should give you the (more common) column-first layout.
Method of the Day: Array#to_sentence
An Oldy but a goody...
<% a = ['hot dogs', 'hamburgers', 'pizza'] %>
I like <%= a.to_sentence(:connector => 'and') %>.
renders...
I like hot dogs, hamburgers, and pizza.
Subscribe to:
Posts (Atom)
|
Who we are...
A handful of ruby on rails developers. We like ruby, rails, seo, and other developer type things. We work at avvo.com.
Other Stuff |