#Ruby Class 1: Ruby’s instance variable and initialize method simplified

We read so many documents about ruby but do you think about some facts that we really don’t know. See below.

1. Instance variables are accessible across the class for that instance

Example:

class Test2
 def one
  @one = 1
  @two
 end
 def two
  @two = 2
  @one
 end
end

Here

t = Test.new
=> 
t.one is what ?
t.two is what ?

Can you guess?

t.one is nil why? t.one will return @two, but it is not initialized yet. We have to call t.two for intitializing it (the variable gets a value).

t.two is what?
Ans: 1
Why? because we already initialized @one by calling t.one above. If not it will also return nil.

So what is the purpose of instance variable if we are not getting its value when initializing the Class (say t = Test.new)

Here is the importance of ‘initialize’ method. Lets change the method named ‘two’ to ‘initialize’

class Test3
 def one
  @one = 1
  @two
 end
 def initialize
  @two = 2
  @one
 end
end

then you try:

t = Test.new
=>    ### See here already declared the variable @two

t.one
=> 2

Nice. So we can access that instance variable anywhere in the class. How is that? 🙂

Advertisement

Author: Abhilash

I'm Abhilash, a web developer who specializes in Ruby development. With years of experience working with various frameworks like Rails, Angular, Sinatra, Laravel, NodeJS, React and more, I am passionate about building robust and scalable web applications. Since 2010, I have been honing my skills and expertise in the Ruby on Rails platform. This blog is dedicated to sharing my knowledge and experience on topics related to Ruby, Ruby on Rails, and other subjects that I have worked with throughout my career. Join me on this journey to explore the exciting world of web development!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: