跳到內容

Ruby 程式碼示例

50% developed
來自華夏公益教科書

此頁面適用於Ruby on Win Intel x86 / Linux AMD64 平臺1.9.2版本。

此頁面以直觀的方式展示了 Ruby 程式碼示例,而不是冗長的解釋,它可以作為語法和程式設計理念的即時參考。還討論了使用務實方法解決問題簡潔的方法。

簡單 I/O

[編輯 | 編輯原始碼]
puts 'Hi!'          # puts the string to stdout
print 'ram:'   # print does not terminate with default \n at the end of execution
name = gets.chomp      # read from stdin
puts "Hi! #{name}"      # interpolates the string, replaces name with its value
print 'c:\books\net\apps\tools'  # outputs c:\books\net\apps\tools
print "c:\books"          # outputs books

字串插值允許變數在執行期間被其值替換

One = 1
puts "#{One} is a number"   # outputs, 1 is a number
puts "%d is a number" % One  # outputs, 1 is a number

%Q 和 %q 是具有特殊屬性的字串字面量

puts %Q^ is Quote friendly^
puts %q# you can type "Quotes"!! #  # outputs, you can type "Quotes"!!

多行字串用 '<<' 字首定義到一個命名的分隔符,例如

puts <<XYZ
Normally programmers try to code to solve the problem and forgets once it is done,
but some explore more, to find a concise opproach to the problem,
and thats makes him !(repetative)
XYZ

Ruby 對字串非常靈活

# choose the one you like
' this '
" this "
%/ this /
%q{ this }
%Q^ this ^
# value => " this "

字串分隔符對是 '', "",但使用 %,%q 和 %Q 字首,我們有 //,{},## 作為分隔符,非官方規則是使用未用於宣告字串本身的分隔符,這樣可以宣告原始字串以避免分隔符衝突

puts %/ '' "" {} ## ^^ /  # outputs, '' "" {} ## ^^

物件是可以使用定義的方法進行處理的東西,即使對於我們周圍的物理物件,也存在使用它們的定義方法,每當我們說“物件”時,它意味著它具有一些方法,透過這些方法可以處理物件

-1.abs                # => 1
'1234567'.length           # => 7 
1234567.to_s.length         # => 7
3.times {print 3}          # outputs, 333
rand(10).times { |x| puts x }    # => random set of numbers from 0 to 10

Ruby 是面向物件的,包括數字、字串甚至 nil 在內的一切都是物件

1.class    # => Fixnum
1.0.class   # => Float
'xyz'.class  # => String
nil.class   # => NilClass

列舉器、範圍、陣列和雜湊

[編輯 | 編輯原始碼]

這些都可以使用 each 方法進行迭代,儘管它們看起來是同義詞,但在計算中存在很大差異,列舉器和範圍幾乎具有固定記憶體長度,因此記憶體效率高且速度快,而陣列雜湊涉及複雜的資料結構以使其成為動態的

列舉器

[編輯 | 編輯原始碼]
5.times.class    # => Enumerator
5.upto(10).class  # => Enumerator
5.upto(10).next   # => 5
(0...10).class  # => Range
(0..9).class   # => Range
(0..2).first   # => 0
(0..2).last    # => 2 
(1..5).next    # invalid, Range class doesent have next method

(0..3).each { |x| print x }       # outputs, 0123
(0...10).reverse_each { |x| print x }  # outputs, 9876543210
(-3..3).each.abs { |x| print x }     # invalid
(-3..3).each { |x| print x.abs }     # outputs, 3210123

# Enumerator doesn't require 'each' to iterate
5.upto(10).class             # => Enumerator
5.upto(10) { |x| print x }        # outputs, 5678910 
(5..10).each { |x| print x }       # outputs, 5678910

陣列是元素的集合,預設情況下,n 個元素的陣列的索引0n-1 列舉,即陣列第一個元素的索引為0

a = [4,6,7,5]  # simple array declaration 
a.length     # => 4
a.rotate     # => [6, 7, 5, 4]
a.sort      # => [4, 5, 6, 7]
a.sort.reverse  # => [7, 6, 5, 4]
a[0]       # => 4
a[3]       # => 5
a[4] = 3     # => 3 ;resulting array is [4, 6, 7, 5, 3]
a << 1      # => [4, 6, 7, 5, 3, 1] ; useful when array size is unknown
a[10] = 0    # => 0 ;resulting array is [4, 6, 7, 5, 3, 1, nil, nil, nil, nil, 0]
a.length     # => 11

允許宣告陣列的陣列、陣列的範圍和混合資料型別的陣列,面向物件

hex = [(0..9),('A'..'F')]
hex.each { |x| x.each { |y| print y }}  # outputs, 0123456789ABCDEF

# declare an array of arrays
nums = [[0,1], [2,3,4,5,6,7], [8,9], ['A','B','C','D','E','F']]
binary = nums[0]             # => [0, 1]
octal = nums[0] + nums[1]        # => [0, 1, 2, 3, 4, 5, 6, 7]
decimal = nums[0] + nums[1] + nums[2]  # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
hexadecimal = nums.flatten        # => [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F']
octal = (binary + octal).uniq      # => [0, 1, 2, 3, 4, 5, 6, 7]

a = [0, 1, 2, 3, 4, 5]  # array of 6 elements
b = a.map { |x| 2**x }  # => [1, 2, 4, 8, 16, 32]

雜湊關聯陣列,它是一組及其關聯的

capitals = {         
:france => 'Paris',
:England => 'London'
}
capitals[:westbengal] = 'Kolkata'   # append a new element
capitals[:karnataka] = 'Bengaluru'  # change an element's association

迭代器和程式碼塊

[編輯 | 編輯原始碼]

迭代器

[編輯 | 編輯原始碼]
alias chant print
108.times {chant 'Hare Krishna!'}  # see the change for yourself

程式碼塊

[編輯 | 編輯原始碼]
def iterator
    yield 'yield, '
    	yield 'blocks,'
	yield 'Ruby'
end
iterator {|yeilded| print "use #{yeilded}"}  # outputs, use yield, use blocks, use Ruby
華夏公益教科書