4 ms·
The first example's use case has benefits beyond just shorter code. When writing ruby, I try to code as functionally as possible, and so I built myself a Ruby v
by SeoxyS 14y ago
The first example's use case has benefits beyond just shorter code. When writing ruby, I try to code as functionally as possible, and so I built myself a Ruby version of a construct stolen from Lisp, which I use for this exact purpose:
def let; yield; end
let do |b = ["24 Dec 2011", "23 Jan 2013"].map {|d| Date.parse(d) }|
puts "#{b.first} to #{b.last} is #{(b.last - b.first).to_i} days"
end
---
Unfortunately Ruby's parser doesn't understand multiple assignment and default values in block argument declaration when used simultaneously, so you can't do:
let do |(first, last) = ["24 Dec 2011", "23 Jan 2013"].map {|d| Date.parse(d) }|
Though you can do this:
let do |both = ["24 Dec 2011", "23 Jan 2013"].map {|d| Date.parse(d) },
first = both.first, last = both.last|
puts "#{first} to #{last} is #{(last - first).to_i} days"