Ruby中有与F#|>(方法链接)相当的东西吗?

Mar*_*ton 2 ruby f# chaining

我在F#中有一个例子:

let a n = Convert.ToString(n:int32)
Run Code Online (Sandbox Code Playgroud)

我可以说:

3 |> a
Run Code Online (Sandbox Code Playgroud)

评估为"3".Ruby中有类似的构造吗?

这是F#(和其他FP语言)方法的链接,它不是函数组合,也不是Ruby中的方法链接,即返回self的对象,以便可以调用对象上的其他方法a.b.c.d.

Jör*_*tag 5

这在Ruby中很容易实现.直接来自F#参考文档:

let function1 x = x + 1
let function2 x = x * 2

let result = 100 |> function1 |> function2
//> val result : int = 202
Run Code Online (Sandbox Code Playgroud)

这可以用Ruby编写如下:

function1 = -> x { x + 1 }
function2 = -> x { x * 2 }

result = 100.pipe(function1).pipe(function2)
# => 202
Run Code Online (Sandbox Code Playgroud)

通过以下实现Object#pipe:

class Object
  def pipe(callable)
    callable.(self)
  end
end
Run Code Online (Sandbox Code Playgroud)

或者用你的例子:

a = -> n { String(n) }

3.pipe(a)
# => '3'
Run Code Online (Sandbox Code Playgroud)

let f x y = x * y

3 |> f(2)
// > 6
Run Code Online (Sandbox Code Playgroud)

f = -> (x, y) { x * y }

3.pipe(f.curry.(2))
# => 6
Run Code Online (Sandbox Code Playgroud)