Ruby Learning Range

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.