MegaEntry 网络社区与信息交流平台!
Ruby 的方法定义允许为参数设置默认值,不过在带有默认值的参数后面不能出现不带有默认值的参数(允许 * 和 &),也就是说下面的方法定义是不被允许的,解释时会出现 parse error。 还有一点与 C# 不同的是,方法定义不能出现在方法调用的后面。# parse error def Display(args1= "proshea ", args2) end # 允许 def Display(args1= "proshea ", *args2) end # 允许 def Display(args1= "proshea ", &args) end Show() # 出现在 Show 调用之后是错误的 def Show end
def Display(*args) print %Q~#{args.join( "- ")}~ end # proshea-32-WinForm Display( "proshea ", 32, "WinForm ")
1def Display(&block) 2 if block_given? 3 yield(block) 4 else 5 print %Q~没有传入过程对象~ 6 end 7end 8 9def Show() 10 print %Q~Show 方法调用~ 11end 12 13# 没有传入过程对象 14Display() 15# 在 Display 内部调用 Show 方法 16# 注意起始大括号仍然只能和方法名在同一行 17Display(){ 18 Show() 19}
1class Employee 2 def initialize(username, age, &block) 3 @username, @age, @block = username, age, block 4 end 5 6 def Display(txt) 7 # 虽然 @block 是个实例变量,但在此处一定要加上大括号 8 print "#{@block.call(txt)}: #@username-#@age " 9 end 10end 11 12emp = Employee.new( "proshea ", 32){ 13 |txt| 14 txt 15} 16emp.Display( "context ")