With instance and class variables, the @'s are part of the name themselves.
This is a nice thing because you can always tell whether you're
looking at a class variable, a local variable, or an instance
variable.
···
On 7/5/05, Jason Foreman <threeve.org@gmail.com> wrote:
On 7/5/05, Faisal Raja <Raja.Faisal@gmail.com> wrote:
> Hello ,
> Well Im new to programming in Ruby Language ( Infact only an hour back
> i started it ) .
>
> class Student
>
> def initialize(name)
>
> @name = name
>
> end
>
> def show
>
> s = "Name : " + name
> return s
>
>
> end
> end
>
>
> st = Student.new("Abc") ;
> st.inspect
>
> I have Windows Xp Sp2 n when i run this program on console , it doesn't
> show me anything . There is no error but it is also not shwoing me
> anything .
>
you aren't printing anything. Try putting "p st.inspect" instead of
just "st.inspect".
> st.inspect should show info
> st.to_s also doesn't show anything
>
>
> if i write st.show
> it also doesn't work .
this is because you reference 'name' which is a local variable, but
what you meant is to access '@name' which is the instance variable.
Try this instead: s = "Name: " + @name
> I wuld be thankful if u people help me out
> Thanks in advance
>
>
>
attr_accessor is an easy way to set up a read/write instance variable; it creates an accessor method so you can go object.name = "John Smith"
or puts object.name
There's also attr_reader to set up a read-only field, and attr_writer for write-only.
The to_s method is the standard method used to convert an object to a string; so if you define it to be something sensible, you can just print or puts the object directly.
So, we can now do
s = Student.new("John Smith")
puts s s.name = "John P. Smith"
puts s.name