Trying to learn Ruby, and in a tutorial, I came across this code on this page:
class Greeter
def initialize(name = "World")
@name = name
end
def say_hi
puts "Hi #{@name}!"
end
def say_bye
puts "Bye #{@name}, come back soon."
end
end
I am also told that the @name variable is an instance variable, and that it is scoped to ALL methods within the class (in this case, Greeter). I am familiar-ish with JS, and it is getting a bit confusing with regards to scoping. Let me clarify a bit. Here is my understanding of the code in JS:
function Greeter (name){
name = (typeof name === "undefined") ? "World" : name;
function say_hi (name){
alert('Hi ' + this.name);
};
function say_bye (name){
alert('Bye ' + this.name + ', come back soon.');
};
};
So in the ruby example, it appears there is a method called initialize, and I guess in ruby, they get the luxury of defining variable within the parameter? In initialize it defines the var @name. In the JS example, I explicitly abstract the naming of the var name, by declaring this.name to mean the name WITHIN say_hi & say_bye. I understand this to be good coding practice, to differentiate the scoping, even though in this case name remains the same throughout the code, being either "World" if an empty parameter is passed, or the name of the person passed as a parameter. Either way, I am unsure of how the scoping works in Ruby, as I am not aware that this is possible in JS. Take the above JS code, and compare it to :
function Greeter (name){
function say_hi (name){
this.name = (typeof name === "undefined") ? "World" : name;
alert('Hi ' + this.name);
};
function say_bye (name){
this.name = (typeof name === "undefined") ? "World" : name;
alert('Bye ' + this.name + ', come back soon.');
};
};
If I failed to declare the this.name in the sub-methods, it could mean the Greeter class variable name, not the say_hi or say_bye variables name respectively.
Questions:
1 - is the @ in @name required to gain the capability to be visible to ALL methods within the class, or is this convention? If it is convention, what does @ signify? (I am equating this to a variable declared as $this in JQuery, where it signifies that the variable is a JQuery element, different from when you query by $('whatever'))
2 - Is the method initialize acting like a getter/setter method scoped within the Greeter class?
3 - Any other comments about your assumptions of my logic, code and questions are very welcome!