2

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.

the_storyteller
  • 2,335
  • 1
  • 26
  • 37
ss_matches
  • 497
  • 2
  • 5
  • 20
  • 2
    You probably need to read a book to accomplish a task. – Aleksei Matiushkin Mar 05 '18 at 16:55
  • 1
    [Refinemenets](https://ruby-doc.org/core-2.5.0/doc/syntax/refinements_rdoc.html) would do. – Aleksei Matiushkin Mar 05 '18 at 16:55
  • I'm aware I can have a custom instance method. I'm wondering if I can have a custom method like above on an instance of Array – ss_matches Mar 05 '18 at 17:03
  • Possible duplicate of [When monkey patching a method, can you call the overridden method from the new implementation?](https://stackoverflow.com/questions/4470108/when-monkey-patching-a-method-can-you-call-the-overridden-method-from-the-new-i) – the_storyteller Mar 05 '18 at 21:24

3 Answers3

4

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.

Luiz Carvalho
  • 1,549
  • 1
  • 23
  • 46
1

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

neznidalibor
  • 175
  • 8
-1

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
sawa
  • 165,429
  • 45
  • 277
  • 381
  • 3
    While this isn't wrong, it's probably better to do it by defining a `module`, then extending the instance with that module. This is how ActiveRecord works some of its dark wizardry internally. – tadman Mar 05 '18 at 18:08