JavaScript的Function.prototype.bind是否有Ruby等价物?

Tha*_*you 9 javascript ruby

JavaScript欢乐时光乐趣的土地

// make a method
var happy = function(a, b, c) {
  console.log(a, b, c);
};

// store method to variable
var b = happy;

// bind a context and some arguments
b.bind(happy, 1, 2, 3);

// call the method without additional arguments
b();
Run Code Online (Sandbox Code Playgroud)

输出.好极了!

1 2 3
Run Code Online (Sandbox Code Playgroud)

在Ruby中

# make a method
def sad a, b, c
  puts a, b, c
end

# store method to variable
b = method(:sad)

# i need some way to bind args now
# (this line is an example of what i need)
b.bind(1, 2, 3)

# call the method without passing additional args
b.call
Run Code Online (Sandbox Code Playgroud)

期望的输出

1, 2, 3
Run Code Online (Sandbox Code Playgroud)

对于它的价值,我知道JavaScript可以通过传递给第一个参数来改变绑定的上下文.bind.在Ruby中,即使我无法改变上下文,我也会感到高兴.我主要需要简单地将参数绑定到方法.

有没有办法将参数绑定到Ruby的实例,Method这样当我调用时method.call没有附加参数,绑定参数仍然传递给方法?

目标

这是一种常见的JavaScript习惯用语,我认为它在任何语言中都很有用.目标是将方法M传递给接收器R,其中R不需要(或具有)当R执行该方法时要向M发送哪个(或多少个)参数的内在知识.

JavaScript演示如何使用它

/* this is our receiver "R" */
var idiot = function(fn) {
  console.log("yes, master;", fn());
};


/* here's a couple method "M" examples */
var calculateSomethingDifficult = function(a, b) {
  return "the sum is " + (a + b);
};

var applyJam = function() {
  return "adding jam to " + this.name;
};

var Item = function Item(name) {
  this.name = name;
};


/* here's how we might use it */
idiot(calculateSomethingDifficult.bind(null, 1, 1));
// => yes master; the sum is 2

idiot(applyJam.bind(new Item("toast")));
// => yes master; adding jam to toast
Run Code Online (Sandbox Code Playgroud)

Aje*_*i32 6

通常,重新绑定方法不是你在Ruby中做的事情.相反,你使用块:

# This is our receiver "R"
def idiot(&block)
  puts("yes, master; #{block.call}")
end


# Here's a couple method "M" examples
def calculateSomethingDifficult(a, b)
  return "the sum is #{a + b}"
end

def applyJam(object)
  return "adding jam to " + object.name
end

class Item
  attr_reader :name
  def initialize(name)
    @name = name
  end
end


# Here's how we might use it
idiot do
  calculateSomethingDifficult(1, 1)
end
#=> yes master; the sum is 2

# You *can* change calling context too (see instance_exec), but I'd
# discourage it. It's probably better to just pass the object as a
# parameter.
idiot do
  applyJam(Item.new("toast"))
end
#=> yes master; adding jam to toast
Run Code Online (Sandbox Code Playgroud)

如果你真的想要像在JavaScript中那样"绑定"方法,那么它绝对是可能的:

class Method
  def bind *args
    Proc.new do |*more|
      self.call *(args + more)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这应该使您的示例几乎像您最初描述的那样工作:

# make a method
def sad a, b, c
  puts a, b, c
end

# store method to variable
b = method(:sad)

# Get a "bound" version of the method
b = b.bind(1, 2, 3)

# call the method without passing additional args
b.call
Run Code Online (Sandbox Code Playgroud)

如果你需要它,你可以定义Object#bindable_method返回一些BindableMethod你想要的类.对于大多数情况,虽然我认为上述内容适合您.