max max - 1 month ago 15
Ruby Question

How do I destructure a range in Ruby?

Is it possible to use destructuring in ruby to extract the end and beginning from a range?

module PriceHelper
def price_range_human( range )
"$%s to $%s" % [range.begin, range.end].map(:number_to_currency)
end
end


I know that I can use array coercion as a really bad hack:

first, *center, last = *rng
"$%s to $%s" % [first, last].map(:number_to_currency)


But is there a syntactical way to get
begin
and
end
without actually manually creating an array?

min, max = (1..10)


Would have been awesome.

Answer

No, but it's easy enough to make.

module RangeWithBounds
  refine Range do
    def bounds
      [self.begin, self.end]
    end
  end
end

module Test
  using RangeWithBounds
  r = (1..10)
  b, e = *r.bounds
  puts "#{b}..#{e}"
end

Then again, I'd just write "#{r.begin.number_to_currency}..#{r.end.number_to_currency}" in the first place.