Scott
Scott

Reputation: 1222

How to get reference to object you're calling in method?

I am trying to create a method for objects that I create. In this case it's an extension of the Array class. The method below, my_uniq, works. When I call puts [1, 1, 2, 6, 8, 8, 9].my_uniq.to_s it outputs to [1, 2, 6, 8].

In a similar manner, in median, I'm trying to get the reference of the object itself and then manipulate that data. So far I can only think of using the map function to assign a variable arr as an array to manipulate that data from.

Is there any method that you can call that gets the reference to what you're trying to manipulate? Example pseudo-code that I could replace arr = map {|n| n} with something like: arr = self.

class Array
  def my_uniq
    hash = {}
    each do |num|
      hash[num] = 0;
    end
    hash.keys
  end
end

class Array
  def median
    arr = map {|n| n}
    puts arr.to_s
  end
end

Thanks in advance!

Upvotes: 1

Views: 86

Answers (2)

m. simon borg
m. simon borg

Reputation: 2575

dup

class Array
  def new_self
    dup
  end

  def plus_one
    arr = dup
    arr.map! { |i| i + 1 }
  end

  def plus_one!
    arr = self
    arr.map! { |i| i + 1 }
  end
end

array = [1, 3, 5]
array.new_self # => [1, 3, 5]
array.plus_one # => [2, 4, 6]
array # => [1, 3, 5]
array.plus_one! # => [2, 4, 6]
array # => [2, 4, 6]

dup makes a copy of the object, making it a safer choice if you need to manipulate data without mutating the original object. You could use self i.e. arr = self, but anything you do that changes arr will also change the value of self. It's a good idea to just use dup.

If you do want to manipulate and change the original object, then you can use self instead of dup, but you should make it a "bang" ! method. It is a convention in ruby to put a bang ! at the end of a method name if it mutates the receiving object. This is particularly important if other developers might use your code. Most Ruby developers would be very surprised if a non-bang method mutated the receiving object.

Upvotes: 2

archana
archana

Reputation: 1272

class Array
  def median
    arr = self
    puts arr.to_s
  end
end

[1,2,3].median # => [1,2,3]

Upvotes: 1

Related Questions