Given the code:
class Someone
def full_name
if false # on purpose
# We'll never reach this point because of the `false` above
first_name = "Other" # So how this code can affect
# the instance variable?
end
"#{first_name} #{last_name}"
end
def first_name
"First"
end
def last_name
"Last"
end
end
s = Someone.new
s.full_name
# => "Last"
Why s.full_name == "Last"
.
In other words, how first_name
method can be overriden until we don't pass through the if statement ?…
To be clear, why ruby doesn't act as… javascript, for instance:
class Someone {
get full_name() {
if ( false ) {
// In JS, that doesn't override
// first_name
this.first_name = "Other";
}
return this.first_name + ' ' + this.last_name;
}
get first_name() {
return "First";
}
get last_name() {
return "Last";
}
}
let s = new Someone();
console.log("s.full_name() = ", s.full_name);
s.full_name
will be egal to "First Last"
, not to "Last"
as in ruby.
It's my effort to understand ruby, not to blame it! (I love passionnément Ruby)
Thanks a lot for answers.