B A*_*B A 0 ruby methods chain
如何将方法的结果传递给ruby中的另一个方法?例如:
class D
def initialize(text)
@text = text
end
def a s
"hello #{s}"
end
def b s
"hi #{s}"
end
end
Run Code Online (Sandbox Code Playgroud)
所以,我想要做的是将方法a的输出传递给方法b.所以基本上(如果方法不在类中)我可以执行以下操作:
puts b(a "Tom") #=>hi hello Tom
Run Code Online (Sandbox Code Playgroud)
但是,即使这不在一个类中,如果有很多方法也不会很好看,所以必须有更优雅的方法来做到这一点.那么hi hello Tom通过将方法a和b应用于类D的实例来获得输出的正确方法是什么?
更新我只是想让它更清晰一些.例如,在F#中,您可以执行以下操作:
let a s = "hello " + s
let b s = "hi " + s
"Tom" |> a |> b #=> hello hi Tom
Run Code Online (Sandbox Code Playgroud)
这里我们定义了函数a和b,然后将结果传递给下一个函数.我知道它是一种功能性语言,所以做事的方式会有所不同.但我只是想知道Ruby中是否有这样的技巧?
你可以离开 ()
def a s
"hello #{s}"
end
def b s
"hi #{s}"
end
puts b a "Tom"
Run Code Online (Sandbox Code Playgroud)
如果你有很多方法:
puts [:a,:b].inject("Tom"){|result,method| self.send(method,result)}
Run Code Online (Sandbox Code Playgroud)
如果要将这些方法与任何对象(包括Classes)一起使用:
module Kernel
def chain_methods(start_value, *methods)
methods.inject(start_value){|result,method| self.send(method,result)}
end
end
class D
def a s
"hello #{s}"
end
def b s
"hi #{s}"
end
end
class E
class << self
def a s
"hello #{s}"
end
def b s
"hi #{s}"
end
end
end
# Example with instance methods
puts D.new.chain_methods("Tom", :a, :b)
# Example with class methods
puts E.chain_methods("Tom", :a, :b)
# Thanks mudasobwa :
E.chain_methods("Tom", :a, :b, :puts)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
457 次 |
| 最近记录: |