基础部分:
puts -1943.abs
def say_goodnight(name)
yield
puts "Good night, " + name
end
say_goodnight("Shen Bin") { puts "Hi " }
$greeting = "Hello"
@name = "Shen Bin 1"
puts "#$greeting, #@name"
a = [1, 'cat', 3.14]
puts a[-1]
a = [1, 3, 5, 7, 9]
puts a[1, 3]
puts a[1..3]
puts a[1...3]
person1 = "Shen Yan"
person2 = person1
person1[0] = "C"
puts person2
person3 = person1.dup
person1[0] = "S"
puts person3
class File
def File.open_and_process(*args)
result = f = File.open(*args)
if block_given?
result = yield f
f.close()
end
return result
end
end
File.open_and_process("D:/rails.txt", "r") do |file|
while line = file.gets
puts line
end
end
['cat', 'dog', 'horse'].each { |name| print name, " "}
["H", 'A', "B"].collect { |x| x.succ }
a = ['3 4', '5 6', '7 8']
a.each do |line|
v1, v2 = line.split
# print v1 + v2, " "
print Integer(v1) + Integer(v2), " "
end
a = %w{ ant bee cat dog elk }
puts a[1]
b = Hash.new(0) # Hash.new 0
b['key1'] += 1;
puts b['key1']
a = %w{ ant bee cat dog elk }
a.each { |a| puts a if a =~ /\w{2}t/ }
puts '-------------------------'
puts a.grep(/\w{2}t/)
类,对象:
class Song
attr_reader :artist, :duration
attr_writer :artist
attr_accessor :name
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
end
def to_s
"Song: #@name -- #@artist (#@duration)"
end
def duration=(new_duration)
@duration = new_duration
end
end
song = Song.new('a', 'b', 100)
#puts song.inspect
puts song.to_s
song.name = 'c'
song.artist = 'd'
song.duration = 600
puts song.to_s
puts song.name + " | " + song.artist + " | " + String(song.duration)
类变量:
class Song
@@plays = 0
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
@plays = 0
end
def play
@plays += 1
@@plays += 1
puts "This song: #@plays plays. Total #@@plays plays."
end
end
s1 = Song.new('Song1', "Artist1", 234)
s2 = Song.new('Song2', "Artist2", 345)
s1.play
s1.play
s2.play
s1.play
Block,闭包
def fibonacci_up_to(max)
x, y = 1, 1
while x < max
if(block_given?)
yield x
end
x, y = y, x+y
end
end
fibonacci_up_to(1000) { |f| print f, " "}
def n_times(thing)
return lambda { |n| thing * n }
end
p1 = n_times(23)
puts p1.call(3)
puts p1.call(4)
p2 = n_times('Hello ')
puts p2.call(2)
each和collect的区别 --- 返回值不同a = [1, 2, 3]
b = a.each { |i| i*2 }
puts b
c = a.collect { |i| i*2 }
puts c
标准类型:数字/字符串/区间等
a = 123_456_789
puts a
puts a.class
b = "Now is #{
def the(a)
'The ' + a
end
the('time')
} for all good coders..."
puts b
c = %q/generate single-quoted string/
d = %Q!generate double-quoted string!
e = %Q{Secounds/Day: #{24*60*60}}
puts c,d,e
f = <<HERE_DOCUMENT_STRING
Hello, Shen Bin.
We are using Ruby.
HERE_DOCUMENT_STRING
puts f
g = (0 .. 10).to_a
h = ('bar' .. 'bat').to_a
puts g, h
i = (0 .. 10) === 5
j = (0 .. 10) === 15
k = ('a' .. 'j') === 'c'
l = ('a' .. 'j') === 'o'
puts i, j, k, l
如果方法定义的最后一个参数的前缀为&,那么所关联的block会被转换为一个Proc对象,然后赋值给这个参数
class TaxCalculator
def initialize(name, &block)
@name, @block = name, block
end
def get_tax(amount)
"#@name on #{amount} = #{ @block.call(amount) }"
end
end
tc = TaxCalculator.new("Sales Tax") { |amt| amt * 0.075 }
puts tc.get_tax(100)
puts tc.get_tax(250)
使用lambda表达式抽取block
print "(t)imes or (p)lus"
t = gets
print "number: "
m = gets.to_i
if t =~ /^t/
puts ((1..10).collect { |n| n * m }.join(", "))
else
puts ((1..10).collect { |n| n + m }.join(", "))
end
#使用lambda表达式把block抽取出来
print "(t)imes or (p)lus"
t = gets
print "number: "
m = gets.to_i
if t =~ /^t/
calc = lambda { |n| n * m }
else
calc = lambda { |n| n + m }
end
puts ((1..10).collect(&calc).join(", "))
If / case when等表达式也可以有返回值:
a = gets
b = if a.to_i > 0
1
elsif a.to_i == 0
0
else
-1
end
puts b
覆盖已有方法class Fixnum
alias plus +
def +(other)
plus(other).succ
end
end
puts 1+1
a = 3
puts a += 4
puts a+a+a
反引号`以及%x --- 将被操作系统当做命令来执行puts `dir`
puts %x{ echo 'Hello World'! }
在Ruby1.8以后,赋值语句的值总是参数的值而方法的返回值将被丢掉
class Test
def val=(val)
@val = val
return 99
end
end
t = Test.new
a = t.val = 2
puts a
self的作用(区别)
class BrokenApmlifier
attr_accessor :left, :right
def volume=(vol)
# @left = @right = vol
left = self.right = vol
end
end
ba = BrokenApmlifier.new
ba.left = ba.right = 3
ba.volume = 5
puts ba.left
puts ba.right
并行赋值:
x = 0
a, b, c = x, x+=1, x+=1
print a, ' ', b, ' ', c
#交换两个变量的值
a, b = b, a
a = [1, 2, 3, 4]
b, c = a # b == 1, c == 2
b, *c = a # b == 1, c == [2, 3, 4]
b, c = 99, a # b == 99, c == [1, 2, 3, 4]
b, *c = 99, a # b == 99, c == [[1, 2, 3, 4]]
b, c = 99, *a # b == 99, c == 1
b, *c = 99, *a # b == 99, c == [1, 2, 3, 4
嵌套赋值
b, (c, d), e = 1, 2, 3, 4 # b == 1, c == 2, d == nil, e == 3
b, (c, d), e = [1, 2, 3, 4] # b == 1, c == 2, d == nil, e == 3
b, (c, d), e = 1, [2, 3], 4 # b == 1, c == 2, d == 3, e == 4
b, (c, d), e = 1, [2, 3, 4], 5 # b == 1, c == 2, d == 3, e == 5
b, (c, *d), e = 1, [2, 3, 4], 5 # b == 1, c == 2, d == [3, 4], e == 5
#注意,Ruby不支持C或Java中自增(++)和自减(--)运算,需要使用(+=)或(-=)代替。
变量作用域:
x = y = nil # 此处不定义的话程序会抛错
[1, 2, 3].each do |a|
x = a
y = x + 1
end
puts x, y
网络编程:
require 'net/http'
h = Net::HTTP.new('www.yahoo.com', 80)
response = h.get('/')
if response.message == 'OK'
puts response.body.scan(/<img src=".*?"/m).uniq
end
动态创建:
5.times do |i|
File.open('temp.rb', "w") do |f|
f.puts "module Temp"
f.puts " def Temp.var"
f.puts " #{i}"
f.puts " end"
f.puts "end"
end
load "temp.rb"
puts Temp.var
end