#=> method
#质樸版:
def plus(x,y)
z = x + y
return z
end
plus(3, 4)
#一步到位的:
def plus x,y
x+y
end
plus 3,4
#只有overriding没有overloading
#=> block
#制造一个带有block的method:
def hello
yield
end
hello {puts "hello, block"}
#显式的告诉你这是怎么一回事(并不完全相同:
def hello &block
block.call
end
hello {puts "hello, block"}
#=> lambda and block
# lambda 和 Proc:
lambda{}
Proc.new{}
=begin
lambda和Proc的一点点区别:
Proc中return会跳出当前作用域
lambda中return不会跳出当前作用域
=end
#=> block example
#一些常用的block的例子:
[1,2,3,4,5].each{|i| puts i}
[1,2,3,4,5].each_with_index{|i, index| puts i, index}
[1,2,3,4,5].map{|i| i**2 }
[1,2,3,4,5].select{|i| i%2==0 }
[1,2,3,4,5].reject{|i| i%2==0 }
[1,2,3,4,5].inject{|sum, i| sum += i}
#=> class
# 正常的class实现:
class Bird
attr_accessor :name, :sex
def initialize name
@name = name
end
def self.fly
puts "bird can fly"
end
def say
puts "i am #{@name}"
end
end
bird = Bird.new("didi")
bird.sex = "male"
Bird.fly
Ruby语言 (二)
最新推荐文章于 2024-07-27 06:13:26 发布