Thursday, April 4, 2013

Rails ActiveRecord + PostgreSQL + Ruby Functional Programming = MAGIC

Let's combine the Postgres SQL length function with ActiveRecord Relation magic to get an array of the lengths of each product name.  Note the the following code is running in the Rails Interactive Ruby (irb) Console.


>> a = Product.select('length(name)').order('name').limit(300).map {|i| i['length'].to_i}
  Product Load (2.5ms)  SELECT length(name) FROM "products" ORDER BY name LIMIT 300
=> [58, 79, 90, 103, 41, 30, 43, 57, 70, 55, 49, 44, 39, 91, 115, 126, 48, 35, 45, 75, 57, 53, 67, 55, 56, 47, 84, 74, 83, 82, 80, 51, 44, 91, 86, 34, 38, 82, 86, 52, 56, 63, 120, 54, 66, 61, 32, 60, 99, 36, 40, 36, 60, 40, 70, 58, 53, 56, 67, 102, 77, 56, 40, 84, 59, 61, 59, 54, 50, 52, 62, 73, 57, 69, 44, 60, 45, 54, 48, 78, 36, 45, 61, 67, 78, 92, 45, 63, 64, 59, 68, 65, 64, 111, 71, 66, 70, 87, 50, 85, 94, 80, 106, 47, 48, 102, 36, 81, 82, 38, 67, 94, 84, 102, 62, 80, 72, 65, 49, 64, 46, 56, 53, 46, 56, 33, 32, 37, 43, 71, 66, 75, 54, 70, 40, 70, 39, 70, 86, 93, 55, 52, 59, 43, 56, 45, 23, 28, 61, 36, 63, 67, 61, 98, 53, 82, 85, 92, 63, 43, 55, 39, 31, 36, 103, 59, 68, 34, 53, 74, 71, 71, 72, 56, 50, 43, 56, 54, 84, 61, 66, 106, 63, 76, 36, 68, 64, 56, 46, 50, 48, 82, 35, 44, 53, 33, 68, 65, 58, 29, 34, 70, 50, 54, 75, 86, 57, 52, 48, 66, 53, 69, 33, 77, 73, 57, 70, 55, 40, 43, 81, 83, 97, 68, 60, 103, 69, 107, 50, 45, 38, 98, 72, 57, 66, 107, 74, 78, 75, 78, 48, 63, 41, 75, 46, 80, 73, 103, 102, 91, 41, 68, 50, 57, 42, 41, 86, 97, 44, 40, 36, 83, 83, 66, 57, 49, 46, 51, 78, 64, 39, 90, 35, 43, 24, 46, 73, 59, 59, 63, 84, 66, 31, 43, 80, 77, 96, 73, 75, 38, 57, 66, 24, 72, 38, 36, 32, 91, 90, 29]


Use Ruby's functional reduce method to find the largest field length value:


>> a.reduce(0) do |max, value|
?>       max = value if value > max
>>       max
>>   end
=> 130
>>



Sponsor Ads(Please visit one if you liked this article. Thanks!)

1 comment:

  1. Excellent Blogger. Very interesting to read. I really love to read such a nice post. Thanks! keep rocking.Ruby on Rails Online Course India

    ReplyDelete