2015-02-23 76 views
-1

是否有可能根据输入类型编写一种行为不同的方法?我试图写出一个这样的行为采用参数或块的方法

hello("derick") 
#=> "hello derick!" 

hello do 
    "derick" 
end 
#=>"<hello>'derick'<hello/>" 

回答

1

是的,它可能在Ruby中。使用block_given?你可以检查一个块是否被传递并执行该块,否则返回任何其他结果。

def hello(s=nil) 
    if block_given? 
    "<hello>'#{yield}'</hello>" 
    else 
    "hello #{s}" 
    end 
end 

puts hello("derick!") 

puts (hello do 
    "derick" 
end) 

HTH

相关问题