一般来说,用花括号括起来的代码段,称之为block
Some codes segmetn in “The Book for Ruby” can’t run successful in Ruby 2.3
like below code:
a = “hello world”.split(//).each{ |x| newstr << x.capitalize }
will throw undefined variable, so I change the code in below code and let it
run
# block example
p [1, 2, 3, 4, 5].collect { |number| number + 1 }
p [1, 2, 3, 4, 5].select { |number| number.odd? }
p [1, 2, 3, 4, 5].detect { |number| number.even? }
b3 = [1,2,3].collect{|x| x*2}
p b3
b4 = ["hello","good day","how do you do"].collect{|x| x.capitalize }
p b4
b5 = ["hello","good day","how do you do"].each{|x| x.capitalize }
p b5
b6 = ["hello","good day","how do you do"].each{|x| x.capitalize! }
p b6
# output: ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
a1 = "hello world".split(//)
p a1
=begin
output:
H
HE
HEL
HELL
HELLO
HELLO
HELLO W
HELLO WO
HELLO WOR
HELLO WORL
HELLO WORLD
=end
newstr = ""
a1.collect{ |x| newstr<< x.capitalize; puts newstr; }
#define diff proc using diff format
a = Proc.new{|x| x = x*10; puts(x) }
b = lambda{|x| x = x*10; puts(x) }
c = proc{|x| x.capitalize! }
a.call(10);
b.call(10);
p c.call("test");
#pass argument to block
def caps( anarg )
yield( anarg )
end
caps( "a lowercase string" ){ |x| x.capitalize! ; puts( x ) }
#named proc and yield
a = lambda{ puts "one" }
b = lambda{ puts "two" }
c = proc{ puts "three" }
def abc3( a, b, c, &d)
a.call
b.call
c.call
#below two code is same
d.call #<= block &d
yield #<= also block &d
end
abc3(a, b, c){puts "four"}
#pass x, y, z to block
def xyz
x = 1
y = 2
z = 3
yield( x, y, z )
end
xyz{ |a,b,c| puts(a+b+c) }
# the yield will pass 100 to block instead of "hello world"
a = "hello world"
def foo
yield 100
end
puts( a )
foo{ |a| puts( a ) } # 100
puts( a ) # Hello world