Wednesday, June 27, 2007

Ruby Block比较


class Array
def find
for i in 0 ... self.length
return self[i] if yield self[i]
end
return nil
end
end

a = [1, 2, 3, 4, 5]
puts a.find { |i|
i == 4
}
# error syntax
puts a.find do |i|
i == 4
end
# {...}比do...end块的结合能力强。例如:
#
# foobar a, b do .. end # foobar 是带块的方法
# foobar a, b { .. } # b 成了带块的方法

No comments :