Ruby Haiku - List Specific Days of the Week
Recently I had to populate a drop down menu with the dates of every Sunday for the year up to the present day.
Ruby makes this so freaking easy:
start_date = Date.new(year=2011, month=1, date=1)
end_date = Date.today
my_array = (start_date..end_date).select { |p| [0, 6].include? p.wday }
( Ruby == <3 )
Happy coding!
Ruby Haiku - Sorting an Array of Hashes
I'm constantly amazed at how easy it is to do (seemingly) complex tasks in Ruby. I was recently faced with having to manipulate a large dataset for a report and give the user the ability to sort the data. Rather than deal with multiple queries to the database I queried once, grabbed what I needed and proceeded to manipulate the data and shove it in a data structure for use in display. This being a Ruby on Rails site, I chose a Ruby array of hashes as the data structure.
Example:
user_billing = [{:name=>"Eric", :location=>"Florida", :billing =>10000}, {:name=>"Adam", :location=>"North Carolina", :billing =>5000}]
Sort it based on name:
user_billing.sort_by { |billing| billing[:name] }
Result:
[{:billing=>5000, :location=>"North Carolina", :name=>"Adam"}, {:billing=>10000, :location=>"Florida", :name=>"Eric"}]
Now we can put it in a block:
user_billing.sort_by { |billing| billing[:name] }.each do |billing|
puts "#{billing[:name]}, #{billing[:location]}, #{billing[:billing]}"
end
Displays:
Adam, North Carolina, 5000
Eric, Florida, 10000
Pretty cool and so simple.
Happy coding!