There are two ways this question can be read:
- Technically, why does the indexing solution work, but not the
first one?
The reason is that in order to be able to use foo.bar = :baz, foo's class has to implement the bar= method.
class X
def initialize(y)
@y = y
end
def y
@y
end
end
x = X.new(3)
x.y # => 3
x.y = 7 # => NoMethodError: undefined method `y=' for #<X:0x007fb272726d80 @y=3>
class X
def initialize(y)
@y = y
end
def y
@y
end
def y=(new_y)
@y = new_y
end
end
x = X.new(3)
x.y # => 3
x.y = 7
x.y # => 7
The core library does implement Array#[]=, but does not Array#first=.
- What is the reason they decided not to implement
Array#first=?
The first method is actually part of Enumberable and if one class implemented first=, it would look inconsistent if there was no implementation of Enumerable#first=.
And this can't happen because for some enumerables such method doesn't make sense (Enumerator). It will also require more of you to get the enumerable functionality. As of right now, for a class to become enumerable, it just needs to implement an each method and include the Enumerable module.
Array#[]=, but there is noArray#first=. Are you asking why they didn't put one?Array#first=. It's as simple as that. IsArray#first=needed? No, because one can use[]=. IsArray#first(which we have) needed? No, because one can use Array#[] (which, incidentally, is as different fromArray[]=as night is from day). So why do we haveArray#firstbut notArray#first=? Because those who argued for the addition of the latter carried the day.