Working through some code examples and came across this snippet, edited here for brevity:
class Year
attr_reader :number
def initialize(number)
@number = number
end
def a(str)
puts str
end
def %(other)
number % other # why number instead of @number
end
def my_func()
(self a "hello") # error
end
private
def divisible_by?(i)
(self % i) == 0 #Operator precedence binding self and % together?
end
end
I'm looking to understand why:
the call to (self % i)
doesn't require a space between the self
and %
, I'm guessing it has something to do with operator precedence?
Why does, within the method definition for %(other)
the method refer to number
, I would've expected it to have to refer to the instance variable @number
.
Any help would be appreciated and/or links to ruby docs that would help me explain this. ty in advance
why
number
instead of@number
Because you have defined a reader/getter, might as well use it. Today method number
is backed by an instance variable, tomorrow it's computed (or lazily instantiated, etc.). By using the method and not its internals, you shield yourself from cascading changes. It's called "encapsulation". But you could have used the variable, it's just not a good practice.
the call to (self % i) doesn't require a space between the self and %, I'm guessing it has something to do with operator precedence?
No. Nothing to do with precedence. There was no ambiguity in the spaceless form and ruby was able to parse it successfully, that's why it's allowed.