One
Overview
Range represents a range in Ruby. Represents the method "..." and "...". The former indicates a closing interval:
The elements in range can be numbers, strings, and custom interval objects
(1..10). Each{|i| puts i} #1 2 3 4 5 6 7 8 9 10
(1 ... ). Each{|i| puts i} #1 2 3 4 5 6 7 8 9
1.1
Common methods
Range has the ability to enumerate, so it has all the methods of enumerable, with a detailed reference to the previous Ruby enumerable
Range has some unique methods:
Rng.first Rng.begin returns the first element
Rng.last Rng.end returns the last element
It is important to note that: no matter (1). 10) (1 ... 10) The first one is 1 and the last one is 10, which is not the same as the result of the traversal.
Puts "#{(1..10). First}: #{(1..10). Last}" #1:10
Puts "#{(1...10). first}:#{(1...10). Last}" #1:10
1.2 Custom intervals
Custom interval, only two methods need to be rewritten
<=> for custom comparison objects
SUCC used to generate the next element
The following is a simple example:
#!/usr/bin/ruby
#class of Weekday
Class WeekDay
weeks=["Sunday", "Monday", "Tuesday", "Wensday", "Thursday", "Friday", "Sartday"]
Attr_accessor:weekdayvalue
Def initialize (value)
If Weeks.include? (value)
@weekdayValue =value
End
End
def To_num
Weeks.index (@weekdayValue) if @weekdayValue
End
def <=> (Other)
Self.to_num<=>other.to_num
End
def SUCC
Raise "Week Error" if Self.to_num () >7
Weekday.new (Weeks[self.to_num () +1])
End
def WeekDay (value)
Weekday.new (value)
End
def to_s
@weekdayValue
End
End
Mons=weekday.new ("Monday")
Fris=weekday.new ("Friday")
Puts MONS.SUCC
Puts "#{mons}:#{mons.to_num ()}"
Puts FRIS.SUCC
Puts "#{fris}:#{fris.to_num ()}"
Ra= (Mons. Fris)
ra.each{|week|
Puts week
}
Ruby Learning Range