我可以为现有的Ruby类添加自定义方法吗?

时间:2018-03-05 16:53:17

标签: ruby methods

我接受了一次练习,我应该像这样练习:

[1,2,3,4].custom_method(arg) 

我不知道如何做到这一点或是否可以做到。

3 个答案:

答案 0 :(得分:2)

要向所有数组对象添加方法,您需要覆盖它们,如下所示:

class Array
  def custom_method(multiplier)
    self.map{ |e| e*args }
  end
end

[1,2,3,4].custom_method(2)

现在,我们需要有关您想要做的更多信息。

答案 1 :(得分:0)

您还可以使用instance_eval仅将新方法分配给实例本身。 你可以尝试做这样的事情:

my_array = [1,2,3,4]

my_array.instance_eval do
  def custom_method(args) do
    # do whatever you need to here
  end
end

my_array.custom_method(args) # you would invoke this with your arguments
                             # whatever they may be

Source

答案 2 :(得分:-1)

看起来你想在一个对象上使用单例方法。但我认为这样做没有任何意义,除非在至少两个不同的场合可以引用该对象:定义方法时,以及调用方法时。所以,为了让它有意义,你至少必须将该对象分配给变量或其他东西。然后,有一些方法可以在其上定义单例方法。

一种方法是直接定义它:

map

另一种方法是将其定义为其单例类的实例方法。

// you can probably came up with a more meaningful name
public static Petition mapEntryToPetition(Map.Entry<String, List<AuditRegister>> entry) {
    Petition petition = new Petition();
    PetitionData data = new PetitionData();
    data.setUUID(entry.getKey());
    petition.setData(data);
    petition.setRegisters(entry.getValue());
   return petition;
}
相关问题