如何使用调用、应用和绑定在Ruby中的对象上强制使用类似于JavaScript的方法

How to force methods on objects in Ruby similar to JavaScript using call, apply and bind

本文关键字:对象 方法 JavaScript 类似于 调用 何使用 应用 Ruby 绑定      更新时间:2023-09-26

在JavaScript中,您可以使用调用、应用或绑定方法将方法强行插入对象。我很好奇Ruby中是否有类似的东西。

var item = {
    color:"green"
};

function getColor(){
    return this.color
};

getColor.call(item);  

您可以在Ruby中执行几乎相同的操作:

item = { 
  color: 'green' 
}
get_color = ->(arg) { 
  arg[:color] 
}
get_color.call(item)  # => "green"

->(foo) { ... }lambda { |foo| ... } 的缩写

另一种选择是使用Ruby类系统:

item = Item.new
item.define_singleton_method(:color) do
  "something"
end
item.color
=> "something"

您可以将bindUnboundMethod连接到对象,但仅当对象是UnboundMethod:的owner的实例时

class Super
  def m(arg) "super #@i #{arg}" end
end
class Sub < Super
  def m(arg) "sub #@i #{arg}" end
  def initialize; @i = 'sub' end
end
class Unrelated
  def m(arg) "unrelated #@i #{arg}" end
end
o = Sub.new
um = Super.instance_method(:m)
bm = um.bind(o)
bm.('works')
# => 'super sub works'
um = Unrelated.instance_method(:m)
bm = um.bind(o)
# TypeError: bind argument must be an instance of Unrelated