English 中文(简体)
如何计算:不包括第一种数值的Ruby Tir
原标题:How to: Ruby Range that doesn t include the first value
  • 时间:2010-12-22 17:41:50
  •  标签:
  • ruby

With Ranges in Ruby you can do 0..5 to include all numbers between and including 0 and 5. You can also do 0...5 to include the same numbers except 5 is not included.

(1..5) === 5
=> true
(1...5) === 5
=> false
(1...5) === 4.999999
=> true

是否有办法排除第一个数字,而不是最后的数字来取得这样的结果?

(1...5) === 1
=> false
(1...5) === 1.00000001
=> true
最佳回答

没有,这种范围没有内在支持。 您不妨推出自己的<代码>。 如果有必要采取这种行动,那么类同。

问题回答

Not natively with a Range. You can mess with its mind but you re better off using an incremented first value. This is ugly but:

[(1..5).to_s].map{ |s| a,b=s.split( .. ).map{|i| i.to_i}; (1+a .. b) } #=> [2..5]

Range.new(*[(1..5).to_s].map{ |s| a,b=s.split( .. ).map{|i| i.to_i}; [1+a,b] }.flatten) #=> 2..5

irb(main):004:0> asdf = (1..5)
=> 1..5
irb(main):005:0> Range.new(asdf.min.succ, asdf.max)
=> 2..5

无代表认为是过分的。

除只发送<条码>,第1条_arg.succ,而不是<条码>,第1条_arg? 无,对此没有特别支持。

您可以mon骑马,添加一种方法,以掌握你想要的方式。 注

class Range
    def exclusive()
        Range.new(self.first+1, self.last-1)
    end
end

(1..5).exclusive === 5
==>false
(1..5) === 5
==>true

了解骑马托车,因为它改变了现有班级的功能。 在本案中,这样做可能更好,但鉴于这个问题,这是一个可以接受的答案。





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签