ss_matches
ss_matches

Reputation: 517

Can I add a custom method to an existing Ruby class?

I was given an exercise, in which I was supposed to implement like this:

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

I have no idea how this would be done or if it can be done.

Upvotes: 2

Views: 2413

Answers (3)

neznidalibor
neznidalibor

Reputation: 175

You can also assign the new method only to the instance itself using instance_eval. You can try doing something like this:

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

Upvotes: 1

sawa
sawa

Reputation: 168101

Looks like you want a singleton method on an object. But I don't think it makes any sense to do that unless that object can be referred to in at least two different occasions: when the method is defined, and when the method is called. So, in order to let it make sense, you at least have to assign that object to a variable or something. Then, there are some ways to define a singleton method on it.

One way is defining directly on it:

a = [1,2,3,4]

def a.foo
  "foo"
end

a.foo # => "foo"
[1, 2, 3].foo # >> NoMethodError: undefined method `foo' for [1, 2, 3]:Array

Another way is to define it as an instance method of its singleton class.

b = [1,2,3,4]

class << b
  def foo
    "foo"
  end
end

b.foo #=> "foo"
[1, 2, 3].foo # >> NoMethodError: undefined method `foo' for [1, 2, 3]:Array

Upvotes: -1

Luiz Carvalho
Luiz Carvalho

Reputation: 1419

To add a method to all array objects, you need override them, like this:

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

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

Now, we need more information about what you want to do.

Upvotes: 4

Related Questions