Ruby 代码示例
外观
此页面仅适用于Ruby on Win Intel x86 / Linux AMD64 平台的1.9.2版本。
此页面以直观的方式展示了 Ruby 代码示例,而不是冗长的解释,它可以作为语法和编程理念的即时参考。还讨论了使用务实方法解决问题简洁的方法。
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 个元素的数组的索引从0 到n-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