I want to store newly created Person instance inside the class variable objects, but not sure how to reference the current instance from the constructor.
class Person
##objects = {}
def initialize(key)
##objects[key] = something
end
Ideally, the result is to be able to access the dictionary of Person objects through Person.objects
Simply, in constructor function, self will refer to the current instance.
class Person
##objects = {}
def initialize(key)
##objects[key] = self
puts self # it will print the id of the current instance
end
end
Same way, if you write self in a class method, it will refer to the the class.
But from your question, you seem to be doing something like Person.objects, and it won't work, and will output the following line:
NoMethodError: undefined method `objects' for Person:Class
So, you need to write a class method for it to let the outside world access objects.
def self.objects
##objects
end
Well, there are other ways as well to access the class variables, please have a look at this question.
Related
I've been reading my textbook, and we have come to classes and the keyword self came up. I've been reading some tutorials on tutorialpoint and have read a bunch of SO questions, but for some reason it just isn't clicking in my head Use of ruby Self, so I decided I would tinker around with some examples
Consider
class Box
# Initialize our class variables
##count = 0
def initialize(w,h)
# assign instance avriables
#width, #height = w, h
##count += 1
end
def self.printCount()
puts "Box count is : ###count"
end
end
# create two object
box1 = Box.new(10, 20)
box2 = Box.new(30, 100)
# call class method to print box count
Box.printCount()
Why will we get an error if we remove self. from our printCount() method? I know that self is important to distinguish between class variables and instance variables like in my example #width,#height and ##count.
So what I think is that since I am trying to modify the class variable ##count, I need to use the .self keyword since I am trying to modify a class variable. Thus whenever we want to change a class variable we must use the form def self.methodName.
Is my thought process correct?
There are two types of methods you are using here: instance methods and class methods. As you know, Ruby is an object oriented programming language, so everything is an object. Each object has its own methods that it can call. Let's look at your code
class Box
# Initialize our class variables
##count = 0
def initialize(w,h)
# assign instance avriables
#width, #height = w, h
##count += 1
end
def self.printCount()
puts "Box count is : ###count"
end
end
When you create a method with self.method_name, you are creating the method for the class itself. So the object of Box has a method called printCount(). That is why you can directly call the method.
Box.printCount()
However, if you declare a new instance of the class Box, calling printCount() would result in an error.
box1 = Box.new(1,1)
box1.printCount() #=> undefined method `printCount'
This is because box1 is an instance of the class Box, and the printCount method is only accessible to the class Box.
If you remove the self before the method printCount, it will become an instance method, and then box1 will have access to that method, but then the class Box will not.
And a few semantics, Ruby uses snake_case for method names, so printCount should be print_count. This is just standard practice, doesn't really affect how the code runs.
Also, you need to be careful with class variables, ie ##count. They don't behave as you would expect in Ruby. It does not just belong in the class it is declared in, it is also part of any of its descendants.
For example, let's say I define a new class call SmallBox and inherit from Box.
box1 = Box.new(1,1)
box1 = Box.new(1,1)
Now, the count should be 2 for Box. However, if you try to access the ##count from my new class,
class SmallBox < Box
p ##count
end
This would print 2 as well.
Any changes to the class variable from the descendants will change its value.
For example, I declare an instance of SmallBox, which would add 1 to ##count. You can see if you check the count in Box, it also added 1.
small1 = SmallBox.new(1,1)
class SmallBox
p ##count #=> 3
end
class Box
p ##count #=> 3
end
I would like to provide a more concrete definition which clarifies the lookup algorithm.
First, let's define self. self in Ruby is a special variable that always references the current object. The current object (self) is the default receiver on method calls. Second, self is where instance variables are found.
class MyClass
def method_one
#var = 'var'
method_two
end
def method_two
puts "#var is #{#var}"
end
end
obj = MyClass.new
obj.method_one
Above, when we call method_one, self will refer to the object instantiated, since we invoked method_one on an explicit receiver (the object instance). so self.method_one in the method definition in the Class will refer to the object instance not the Class object itself. #var will be stored in self. Note that when method_two is called, since there is no default receiver, the receiver is self. So when method_two is called, we remain in the same object instance. That is why #var in method_two will refer to the same #var in method_one. It is the same object.
Ruby supports inheritance. So if we call a method on self and it is not defined in its class, then Ruby will search for the instance method in the superclass. This happens until Ruby gets to BasicObject. If it cannot find the method in any of the superclasses, it raises a NoMethodError.
Now there is another important piece to the inheritance chain. There is an anonymous class called the singleton class that Ruby will inject into this inheritance chain. Where in the inheritance chain? It inserts it right before the original class of the object. This way, when ruby searches for the method, it will hit the singleton class before it hits the original class of the object.
> msg = 'Hello World'
=> "Hello World"
> def msg.hello_downcase
> puts 'Hello World'.downcase
> end
=> :hello_downcase
> msg.downcase
=> "hello world"
> msg2 = 'Goodbye'
=> "Goodbye"
> msg2.hellow_downcase
NoMethodError: undefined method `hellow_downcase' for "Goodbye":String
The lookup algorithm:
msg -> Anonymous Singleton Class (hello_downcase method is in here) -> String -> Object
msg2 -> String -> Object
In the above example, msg and msg2 are both object instances of the String class object. But we only opened up the singleton class of msg and not msg2. the hello_downcase method was inserted into the singleton class of msg. It's important to note that when we add another singleton method, it will reopen the same singleton class again; it will not open another anonymous singleton class. There will only be one anonymous singleton class per instance.
Notice above I said the String class object, and not just the String class. That's because a class itself is an object. A class name is simply a constant which points to an object:
class HelloWorld
def say_hi
puts 'Hello World'
end
end
More precisely, in the above example, HelloWorld is a constant which points to an object, whose class is Class. Because of this, the lookup chain will be different for HelloWorld and its instances. An instance's class is HelloWorld. And when we invoke a method with the instance as the receiver, inside HelloWorld method definitions, self will refer to that instance. Now HelloWorld's class is Class (Since Class.new is what created HelloWorld). And because of this, its inheritance chain looks different:
#<HelloWorld:0x007fa37103df38> -> HelloWorld -> Object
HelloWorld -> Class -> Module -> Object
Now since HelloWorld is also an object, just as with instances, we can open up its Singleton Class.
class HelloWorld
def self.say_hi_from_singleton_class
puts 'Hello World from the Singleton Class'
end
end
HelloWorld.say_hi_from_singleton_class
The lookup algorithm:
HelloWorld -> Anonymous Singleton Class -> Class (this is where the new method is defined) -> Module -> Object
Why does this work? As mentioned, a method call with an explicit receiver changes the value of self to point to that object. The second thing that changes the value of self is a class definition. self inside of the class definition refers to the class object, referred to by constant HelloWorld. This is only the case while inside of the class definition. Once we leave the class definition, self will no longer refer to the constant HelloWorld.
> puts self
main
> class HelloWorld
> puts self
> end
HelloWorld
=> nil
> puts self
main
Ultimately, there are two ways in which the special variable self will change: 1) when you call a method with an explicit receiver, 2) inside of a class definition.
In the following example everything is logical for me:
class Something
def initialize
#x=101
end
def getX
return #x
end
end
obj = Something.new
puts obj.getX
=>101
Something.new will create new instance of class Something with instance variable #x which will be visible to all methods of class Something.
But what will happen in second example without initialize(constructor) method.
class Something
def bla_bla_method
#x=101
end
def getX
return #x
end
end
obj = Something.new
puts obj.getX
=>nil
obj.bla_bla_method
puts obj.getX
=>101
So now bla_bla_method when called will create(like constructor) new instance_variable #x and will add that instance variable in "instance variable table" which is available to all methods again?
So now if i add new method "new_method" in class Something(in second example):
def new_method
#x=201
end
...
obj.bla_bla_method
puts obj.getX
=>101
obj.new_method
puts obj.getX
=>201
So if im getting this right, every method of class can create new instance variable which is available to all methods of class? And then every method can overwrite that instance variable over and over again(cyclical)?
I'm new to ruby so maybe here i'm doing big mistake or don't understand some basic concept , so dont yell :D
Instance variables for an object can be named and manipulated while the object exists. See the example below, when we are using the irb prompt object:
$ irb
> instance_variables # => [:#prompt]
> #foo # => nil
> instance_variables # => [:#prompt]
> #foo = 1 # => 1
> instance_variables # => [:#prompt, :#foo]
> #foo # => 1
Now, here's a description of Class#new from the docs:
Calls allocate to create a new object of class’s class, then invokes that object’s initialize method, passing it args. This is the method that ends up getting called whenever an object is constructed using .new.
One way to think of this is that initialize is functionally a regular method just like your other instance methods, only it gets called by Class#new to provide us with an easy way of setting default values (among others).
Technically, yes. But consider the notion of Object Oriented programming - Creating real world abstractions in form of classes and objects.
For instance, if you are talking about a student in a school; you know that is an abstractable entity. So you go ahead and encapsulate the common characteristic of student in a class Student.
initialize is a constructor. When you create a new student in your system, you would naturally want to supply few necessary details about him like his name, age and class.
So in initialize method you set those instance variables.
Few students also study in school; so naturally they will acquire some grade and stuff; to instantiate those details about the student, you would want to do that with something like this:
#Student(name, age, class)
kiddorails = Student.new("Kiddorails", 7, 2)
#to grade:
kiddorails.set_grades
#do stuff
So you can mutate and set the instance variables in an object, almost anywhere you want in a class; but the point is - Do it, where it makes sense.
PS: You should always set default values to the instance variables which are not set via initialize in initialize, if needed.
I Just started learning ruby and I don't see the difference between an #instace_variable and an attribute declared using attr_accessor.
What is the difference between the following two classes:
class MyClass
#variable1
end
and
class MyClass
attr_accessor :variable1
end
I searched lot of tutorials online and everybody uses different notation, Does it have to do anything with the ruby version? I also searched few old threads in StackOverflow
What is attr_accessor in Ruby?
What's the Difference Between These Two Ruby Class Initialization Definitions?
But still I am not able to figure out what is the best way to use.
An instance variable is not visible outside the object it is in; but when you create an attr_accessor, it creates an instance variable and also makes it visible (and editable) outside the object.
Example with instance variable (not attr_accessor)
class MyClass
def initialize
#greeting = "hello"
end
end
m = MyClass.new
m.greeting #results in the following error:
#NoMethodError: undefined method `greeting' for #<MyClass:0x007f9e5109c058 #greeting="hello">
Example using attr_accessor:
class MyClass
attr_accessor :greeting
def initialize
#greeting = "hello"
end
end
m2 = MyClass.new
m2.greeting = "bonjour" # <-- set the #greeting variable from outside the object
m2.greeting #=> "bonjour" <-- didn't blow up as attr_accessor makes the variable accessible from outside the object
Hope that makes it clear.
Instance variables are not directly visible outside of the class.
class MyClass
def initialize
#message = "Hello"
end
end
msg = MyClass.new
#message
#==> nil # This #message belongs to the global object, not msg
msg.message
#==> NoMethodError: undefined method `message'
msg.#message
#==> SyntaxError: syntax error, unexpected tIVAR
Now, you can always do this:
msg.instance_eval { #message }
or ask for the variable directly like this:
msg.instance_variable_get :#message
But that's awkward and sort of cheating. Poking around someone else's class may be educational, but your client code shouldn't be required to do it to get reliable results. So if you want clients to be able to see those values, don't make them use the above techniques; instead, define a method to expose the value explicitly:
class MyClass
def message
return #message
end
end
msg.message
# ==> "Hello"
Because you so often want to do that, Ruby provides a shortcut to make it easier. The code below has exactly the same result as the code above:
class MyClass
attr_reader :message
end
That's not a new type of variable; it's just a shorthand way to define the method. You can look at msg.methods and see that it now has a message method.
Now, what if you want to allow outsiders to not only see the value of an instance variable, but change it, too? For that, you have to define a different method for assignment, with a = in the name:
class MyClass
def message=(new_value)
#message = new_value
end
end
msg.message = "Good-bye"
msg.message
# ==> "Good-bye"
Note that the assignment operators are semi-magical here; even though there's a space between msg.message and =, Ruby still knows to call the message= method. Combination operators like += and so on will trigger calls to the method as well.
Again, this is a common design, so Ruby provides a shortcut for it, too:
class MyClass
attr_writer :message
end
Now, if you use attr_writer by itself, you get an attribute that can be modified, but not seen. There are some odd use cases where that's what you want, but most of the time, if you are going to let outsiders modify the variable, you want them to be able to read it, too. Rather than having to declare both an attr_reader and an attr_writer, you can declare both at once like so:
class MyClass
attr_accessor :message
end
Again, this is just a shortcut for defining methods that let you get at the instance variable from outside of the class.
attr_accesor gives you methods to read and write the instance variables. Instance variables are deasigned to be hidden from outside world so to communicate with them we should have attr_ibute accesor methods.
In OOPS we have a concept called encapsulation which means, the internal representation of an object is generally hidden from view outside of the object's definition. Only the Object 'itself' can mess around with its own internal state. The outside world cannot.
Every object is usually defined by its state and behavior, in ruby the instance variables is called internal state or state of the object and according to OOPS the state should not be accessed by any other object and doing so we adhere to Encapsulation.
ex: class Foo
def initialize(bar)
#bar = bar
end
end
Above, we have defined a class Foo and in the initialize method we have initialized a instance variable (attribute) or (property). when we create a new ruby object using the new method, which in turn calls the initialize method internally, when the method is run, #bar instance variable is declared and initialized and it will be saved as state of the object.
Every instance variable has its own internal state and unique to the object itself, every method we define in the class will alter the internal state of the object according to the method definition and purpose. here initialize method does the same, such as creating a new instance variable.
var object = Foo.new(1)
#<Foo:0x00000001910cc0 #bar=1>
In the background, ruby has created an instance variable (#bar =1) and stored the value as state of the object inside the object 'object'. we can be able to check it with 'instance_variables' method and that methods returns an array containing all the instance variables of the object according to present state of the object.
object.instance_variables
#[
[0]: #bar
]
we can see '#bar' instance variable above. which is created when we called the initialize method on the object. this '#bar' variable should not be visible (hidden) by default and so it cannot be seen by others from outside of the object except the object, from inside. But, an object can mess around with its own internal state and this means it can show or change the values if we give it a way to do so, these two can be done by creating a new instance methods in the class.
when we want to see the #bar variable by calling it we get an error, as by default we cannot see the state of an object.
show = object.bar
#NoMethodError: undefined method `bar' for #<Foo:0x00000001910cc0 #bar=1>
#from (irb):24
#from /home/.rvm/rubies/ruby-2.0.0-p648/bin/irb:12:in `<main>'
But we can access the variables by two methods, these two are called setter and getter methods, which allow the object to show or change its internal state (instance variables/attributes/properties) respectively.
class Foo
def bar
#bar
end
def bar=(new_bar)
#bar = new_bar
end
end
We have defined a getter(bar) and setter(bar=) methods, we can name them any way but the instance variable inside must the same as instance variable to which we want to show or change the value. setters and getters are a violation to OOPS concepts in a way but they are also very powerful methods.
when we define the two methods by re-opening the class and defining them, when we call the object with the methods, we can be able to view the instance variables(here #foo) and change its value as well.
object.bar
1
object.bar=2
2
object.bar
2
Here we have called the bar method (getter) which returns the value of #bar and then we have called bar= method (setter) which we supplied a new_value as argument and it changes the value of instance variable (#bar) and we can look it again by calling bar method.
In ruby we have a method called attr_accessor , which combines the both setter and getter methods, we define it above the method definitions inside the class. attr_* methods are shortcut to create methods (setter and getter)
class Foo
attr_accessor :bar
end
we have to supply a symbol (:bar) as argument to the attr_accessor method which creates both setter and getter methods internally with the method names as supplied symbol name.
If we need only a getter method, we can call attr_reader :bar
If we need only a setter method, we can call attr_writer :bar
attr_accessor creates both attr_writer and attr_reader methods
we can supply as many instance variables as we want to the attr_* methods seperated by commas
class Foo
attr_writer :bar
attr_reader :bar
attr_accessor :bar, :baz
end
Because attr_accessor defines methods, you can call them from outside the class. A #variable is only accessible from inside the class.
And another answer more compact (for Java developers)
attr_accessor :x creates the getters and setters to #x
class MyClassA
attr_accessor :x
end
is the same as
class MyClassB
def x=(value) #java's typical setX(..)
#x=value
end
def x
#x
end
end
I'm new to programming and am trying to figure out the purpose of "initialize" in creating a class.
Here's an example:
class Person
def initialize(name)
#name = name
#pet = nil
#home = 'NYC'
end
end
So initializing is to create a bunch of attributes that I can pull out directly by saying Person.name and Person.pet and Person.home right? Is "initialize" just to compact a bunch of variables into one place? Would I accomplish the same thing doing this:
class Person
pet = nil
home = 'NYC'
#not so sure how to replicate the #name here.
end
Wouldn't I be able to access the values with Person.pet and Person.home the same way as I would in the first code?
This is a little tricky in Ruby (as opposed to, say, Java) since both classes and instances of classes are actual objects at runtime. As such, a class has its own set of variables, and each instance of that class also gets its own set of variables (distinct from the class's variables).
When you say
class Person
pet = nil
end
You're setting a variable, pet, which is local only to the class object called Person.
The way to manipulate the variables of an instance of a class is to use the variables in methods:
class Person
def initialize
pet = nil
end
end
Here, pet refers to a local variable of a given instance of Person. Of course, this pet variable is pretty useless as defined, since it's just a local variable that goes away after the initialize function completes. The way to make this variable persist for the lifetime of the instance is to make it an instance variable, which you accomplish by prefixing it with a #. And thus we arrive at your first initialize:
class Person
def initialize
#pet = nil
# And so on
end
end
So, as to why you need initialize. Since the only way to set the instance variables of instances of Person is within methods of Person, this initialization needs to be in some method. initialize is just the convenient name for a method which is automatically called when your instance is first created.
Initialize is a method usually referred as an object constructor. It is used when you call Person.new("Bob") and it will give you an instance of that Person object. The # symbol you see before the variables in the initialize makes the variable an instance variable meaning that variable will only be accessed once you have an instance of that object and it will stay there for the lifetime of that instance.
For example
person = Person.new("Bob")
person.name #Will output Bob
person.home #Will output NYC
Classes are objects and doing this:
class Person
pet = nil
home = 'NYC'
end
is just creating local variables pet and home and will be outside of the scope of the class. This means calling Person.pet and Person.home will just give you an error. I would suggest do a little reading on Object Oriented Programming (OOP) and if you have any more questions throw them in stackoverflow :D
I wan't to set a class variable of a class from the outside(via attr_accessor), and then access it from inside one of its objects. I'm using ruby 1.9.2. This is my code:
class Service
def initialize(id)
#my_id = id
end
class << self
attr_accessor :shared_id
end
def system_id
#my_id + ##shared_id
end
end
If I set Service.shared_id = "A2", and then call Service.new("A").system_id, this doesn't return "AA2". It displays the following error:
uninitialized class variable ##shared_id in Service
The behaviour is like if I didn't set the Service.service_id. Can someone please explain why this happens?
attr_accessor creates methods to manipulate instance variables — it does not create instance or class variables. To create a class variable, you must set it to something:
##shared_id = something
There's no helper method to generate accessor for class variables, so you have to write them yourself.
However, class variables, because of their weird lookup rules, are rarely used — avoided, even. Instead, instance variables at class-level are used.
class Service
#shared_id = thing
class << self
attr_accessor :shared_id
end
def system_id
# use self.class.shared_id; you could add a shared_id helper to generate it, too.
end
end
How about cattr_accessor?
Remember that ##class_var is global for all classes.