Overriding Instance Variable Array's Operators in Ruby

Overriding instance variable array's operators in Ruby

I think you're looking for this:

class Test
def initialize
@myarray = []
class << @myarray
def <<(val)
puts "adding #{val}" # or whatever it is you want to do first
super(val)
end
end
end
attr_accessor :myarray
end

There's a good article about this and related topics at Understanding Ruby Singleton Classes.

Overriding instance variable array’s operators in Ruby and scoping

like this:

# need this or else `moski_call` method is looked up in context of @boxholder
moski_call_output = moski_call

class << @boxholder; self; end.send(:define_method, :<<) { |box|
box.setPositionWithinColumn(moski_call_output)
super(box)
}

Overriding the method for instance variables

Programming is a lot like real life: it is not a good idea to just run around and let strangers touch your private parts.

You are solving the wrong problem. You are trying to regulate what strangers can do when they play with your private parts, but instead you simply shouldn't let them touch your privates in the first place.

class Example
def initialize(numbers = [])
@numbers = numbers.clone
end

def numbers
@numbers.clone.freeze
end

def <<(number)
validate(number)
@numbers << number
self
end

private

def validate(number)
raise ArgumentError, "number must be non-negative, but is #{number}" unless number >= 0
end
end

example = Example.new([1, 2, 3])
example.numbers # [1, 2, 3]
example << 4
example.numbers # [1, 2, 3, 4]
example << -1 # raise ArgumentError

Let's look at all the changes I made one-by-one.

cloneing the initializer argument

You are taking a mutable object (an array) from an untrusted source (the caller). You should make sure that the caller cannot do anything "sneaky". In your first code, I can do this:

ary = [1, 2, 3]
example = Example.new(ary)

ary << -1

Since you simply took my array I handed you, I can still do to the array anything I want!

And even in the hardened version, I can do this:

ary = [1, 2, 3]
example = Example.new(ary)

class << ary
remove_method :<<
end

ary << -1

Or, I can freeze the array before I hand it to you, which makes it impossible to add a singleton method to it.

Even without the safety aspects, you should still do this, because you violate another real-life rule: Don't play with other people's toys! I am handing you my array, and then you mutate it. In the real world, that would be considered rude. In programming, it is surprising, and surprises breed bugs.

cloneing in the getter

This goes to the heart of the matter: the @numbers array is my private internal state. I should never hand that to strangers. If you don't hand the @numbers array out, then none of the problems you are protecting against can even occur.

You are trying to protect against strangers mutating your internal state, and the solution to that is simple: don't give strangers your internal state!

The freeze is technically not necessary, but I like it to make clear to the caller that this is just a view into the state of the example object, and they are only allowed to view what I want them to.

And again, even without the safety aspects, this would still be a bad idea: by exposing your internal implementation to clients, you can no longer change the internal implementation without breaking clients. If you change the array to a linked list, your clients are going to break, because they are used to getting an array that you can randomly index, but you can't randomly index a linked list, you always have to traverse it from the front.

The example is unfortunately too small and simple to judge that, but I would even question why you are handing out arrays in the first place. What do the clients want to do with those numbers? Maybe it is enough for them to just iterate over them, in which case you don't need to give them a whole array, just an iterator:

class Example
def each(...)
return enum_for(__callee__) unless block_given?
@numbers.each(...)
self
end
end

If the caller wants an array, they can still easily get one by calling to_a on the Enumerator.

Note that I return self. This has two reasons:

  1. It is simply the contract of each. Every other object in Ruby that implements each returns self. If this were Java, this would be part of the Iterable interface.

  2. I would actually accidentally leak the internal state that I work so hard to protect! As I just wrote: every implementation of each returns self, so what does @numbers.each return? It returns @numbers, which means my whole Example#each method returns @numbers which is exactly the thing I am trying to hide!

Implement << myself

Instead of handing out my internal state and have the caller append to it, I control what happens with my internal state. I implement my own version of << in which I can check for whatever I want and make sure no invariants of my object are violated.

Note that I return self. This has two reasons:

  1. It is simply the contract of <<. Every other object in Ruby that implements << returns self. If this were Java, this would be part of the Appendable interface.

  2. I would actually accidentally leak the internal state that I work so hard to protect! As I just wrote: every implementation of << returns self, so what does @numbers << number return? It returns @numbers, which means my whole Example#<< method returns @numbers which is exactly the thing I am trying to hide!

Drop the bang

In Ruby, method names that end with a bang mean "This method is more surprising than its non-bang counterpart". In your case, there is no non-bang counterpart, so the method shouldn't have a bang.

Don't abuse boolean operators for control flow

… or at least if you do, use the keyword versions (and / or) instead of the symbolic ones (&& / ||).

But really, you should void it altogether. do or die is idiomatic in Perl, but not in Ruby.

Technically, I have changed the return value of your method: it used to return true for a valid value, now it returns nil. But you ignore its return value anyway, so it doesn't matter.

validate is probably not a good name for the method, though. I would expect a method named validate to return a boolean result, not raise an exception.

An exceptional message

You should add messages to your exceptions that tell the programmer what went wrong. Another possibility is to create more specific exceptions, e.g.

class NegativeNumberError < ArgumentError; end

But that would be overkill in this case. In general, if you expect code to "read" your exception, create a new class, if you expect humans to read your exception, then a message is enough.

Encapsulation, Data Abstraction, Information Hiding

Those are three subtly different but related concepts, and they are among the most important concepts in programming. We always want hide our internal state and encapsulate it behind methods that we control.

Encapsulation to the max

Some people (including myself) don't particularly like even the object itself playing with its internal state. Personally, I even encapsulate private instance variables that are never exposed behind getters and setters. The reason is that this makes the class easier to subclass: you can override and specialize methods, but not instance variables. So, if I use the instance variable directly, a subclass cannot "hook" into those accesses.

Whereas if I use getter and setter methods, the subclass can override those (or only one of those).

Note: the example is too small and simple, so I had some real trouble coming up with a good name (there is not enough in the example to understand how the variable is used and what it means), so eventually, I just gave up, but you will see what I mean about using getters and setters:

class Example
class NegativeNumberError < ArgumentError; end

def initialize(numbers = [])
self.numbers_backing = numbers.clone
end

def each(...)
return enum_for(__callee__) unless block_given?
numbers_backing.each(...)
self
end

def <<(number)
validate(number)
numbers_backing << number
self
end

private

attr_accessor :numbers_backing

def validate(number)
raise NegativeNumberError unless number >= 0
end
end

example = Example.new([1, 2, 3])
example.each.to_a # [1, 2, 3]
example << 4
example.each.to_a # [1, 2, 3, 4]
example << -1 # raise NegativeNumberError

Override for an array instance variable in class

class Player
attr_accessor :moves

def initialize
@moves = []
@moves.define_singleton_method(:<<) do |value|
raise Exception if include?(value)
push(value)
end
end
end

You can add methods only specific to a given object using the Object#define_singleton_method. Ruby is really flexible when it comes to meta programming.

However such tools should be used sparingly. I don't know your specific situation, but you are probably better off not giving direct access to @moves. The best approach might be to define methods in Player that create an indirect and more restrictive interface to the internal representation and give you more control.

Ruby - How to change an instance variable in various objects using map method

The issue you have is that your map function is returning the value of x.var_1 + 1 which is an Integer. When you loop back over it, you're looping over Integers not Foo objects.

You almost have it, you just need to use an assignment operator such as +=to assign val_2 to itself + 1 like this:

newArray = array.map { |x|
x.var_2 += 1
x
}

def showArray(array)

array.each do | var |
puts "Var 1: #{var.var_1} | Var 2: #{var.var_2} | Var 3: #{var.var_3}"
end
end

showArray(newArray)

output:

Var 1: c | Var 2: 2 | Var 3: d
Var 1: e | Var 2: 3 | Var 3: f
Var 1: g | Var 2: 4 | Var 3: h

RUBY instance variable is reinitialized when calling another method

what would be the right way to do something like this ?

my_instance = 0

This creates a local variable instead of calling your setter. Give ruby a hint that you want to call the method:

self.my_instance = 0

Or you can set the instance variable directly:

@my_instance = 0

How to override attr_accessor getter and in rails?

Your problem here is that the getter is returning a new array. You modify the singleton class of the @followers array, but that is not being used in the getter:

def followers
puts 'getter'
['a','new','array']
end

If you want to have a custom getter, then you need to make sure that the getter returns @followers (without changing the underlying reference), or you need to re-decorate the array.

However, what AlexWayne suggested is the proper way to do this. Return a proxy object that handles the redis details:

class FollowersList < SimpleDelegator
def initialize(assoc)
@assoc = assoc
super(_followers)
end

def _reload
__setobj__ _followers
self
end

def _followers
user_ids = $redis.get key
User.find_all user_ids
end

def _key
"speaker#{@assoc.id}followers"
end

# implement your overrides. The _reload method is to force the list to sync
# with redis again, there are other ways to do this that wouldn't do the query
# again
def <<(val)
$redis.lpush key, val.id
_reload
end

#etc
end

Overriding the == operator in Ruby

In Ruby == is just a method (with some syntax sugar on top allowing you to write foo == bar instead of foo.==(bar)) and you override == just like you would any other method:

class MyClass
def ==(other_object)
# return true if self is equal to other_object, false otherwise
end
end


Related Topics



Leave a reply



Submit