1.
puts "第八章再说字符串"
str = 'this/'s you string./n'
puts str
str = "this/'s you string./n"
puts str
def hello(name)
"Welcome ,#{name}!"
end
puts hello("kaichuan")
puts hello("ruby")
2.
str = "Hello,kaichuan,Welcome!"
=begin
=~ 这是一个符号
返回的是一个位置
=end
puts str=~ /kaichuan/
puts str =~ /a/
puts str =~ /ABC/
=begin
!~ 存在返回false
不存在返回true
=end
puts str !~ /kaichuan/
puts str !~ /a/
puts str !~ /ABC/
3.
strdoc =<<DOC_EOF
This is windows2000 or windows98 system.
Windows system is BEST?
Windows2000 running in 12-31-2006,……
DOC_EOF
re = /[w|W]indows(?:98|2000)/
strdoc.gsub!(re,"Windows XP")
re = /[1-9][0-9]/-[1-9][0-9]/-/d/d/d/d/
time = Time.now.strftime("%m-%d-%Y") #得到当前时间
strdoc.gsub!(re, time)
puts strdoc
4.
(1..9).each {|i| print i if i<7}
#each 是一个迭代器
print "/n"
def one_block
yield
yield
yield
end
one_block {puts "This is a block."}
=begin
begin
a = "12".to_i
rescue
end
=end
def one_block
for num in 1..3
yield(num)
end
end
one_block do |i|
puts "This is block#{i}."
end
print "do_something/n"
def do_something
yield
end
do_something do
(1..9).each{|i| print i if i<5}
puts
end
do_something do
3.times{print "Hi!"}
puts
end
5.
class Array
def one_by_one
for i in 0...size
yield(self[i])
end
puts
end
end
arr = [1,3,5,7,9]
arr.one_by_one {|k| print k,","}
arr.one_by_one{|h|print h*h,","}