How to destroy a range in Ruby?

Can ruby ​​be restructured to extract the end and start with 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 very bad hack:

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

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

 min, max = (1..10) 

It would be great.

+6
source share
4 answers

No, Until I proved that Carey Suvoland, the Weekly News of the World, or another tabloid is wrong, I will continue to believe without any evidence that the answer is no; but it's easy enough to do.

 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 I just write "#{r.begin.number_to_currency}..#{r.end.number_to_currency}" .

+2
source

Beginning and the end? I would use:

 foo = 1..2 foo.min # => 1 foo.max # => 2 

Trying to use restructuring for a range is a bad idea. Imagine the dimensions of an array that can be generated, then thrown away, wasting time and processor memory. This is a really great way to DOS your own code if your range ends in Float::INFINITY .


end does not match max : at 1 ... 10, end is 10, but max is 9

This is because start_val ... end_val equivalent to start_val .. (end_val - 1) :

 start_value = 1 end_value = 2 foo = start_value...end_value foo.end # => 2 foo.max # => 1 foo = start_value..(end_value - 1) foo.end # => 1 foo.max # => 1 

max reflects the reality of the values ​​actually used by Ruby when iterating over a range or testing for inclusion in a range.

In my opinion, end should reflect the actual maximum value that will be considered within the range, not the value used at the end of the range definition, but I doubt it will change, otherwise the existing code will affect it.

... more confusing and leads to increased maintenance problems, so its use is not recommended.

+4
source

You can use minmax to break down small ranges:

 min, max = (1..10).minmax min # => 1 max # => 10 
+3
source

Amadan's answer is in order. you just need to remove splat (*) when using it, since it is not needed

eg,

  > "% s to% s"% (1..3) .bounds.map {| x |  number_to_currency (x)}
 => "$ 1.00 to $ 3.00"
0
source

All Articles