Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Is variable is object in ruby?

Tags:

variables

ruby

I heard that everything in ruby is object. I replied in an interview that a variable is an object, and the interviewer said NO. Anybody know the truth?

like image 907
shajin Avatar asked Dec 05 '11 07:12

shajin


People also ask

Is a variable an object in Ruby?

A variable itself is not an object. "A variable in Ruby is just a label for a container. A variable could contain almost anything - a string, an array, a hash. A variable name may only contain lowercase letters, numbers, and underscores. A variable name should ideally make sense in the context of your program."

How do you check if an object is an instance of a class Ruby?

Use #is_a? to Determine the Instance's Class Name in Ruby If the object given is an instance of a class , it returns true ; otherwise, it returns false . #is_a also returns true if the object is an instance of any subclasses.

What does == mean in Ruby?

The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not. str1 = “This is string”


2 Answers

"In ruby, everything is an object" is basically true.

But more accurately, I would say that any value that can be assigned to a variable or returned from a method is an object. Is a variable an object? Not really. A variable is simply a name of an object (also known as a "pointer") that allows you locate it in memory and do stuff with it.

shajin = Person.new()

In this snippet, we have a variable shajin, which points to an object (an instance of the person class). The variable is simply the identifier for an object, but is not the object itself.

I think it was a trick question. Ultimately object orientation is feature for humans to understand complex programs, but computers are not object oriented themselves. Drill down enough layers and objects cease to exist in any language.

So perhaps it's more fair to say: "In ruby, everything important is an object".

like image 89
Alex Wayne Avatar answered Oct 20 '22 22:10

Alex Wayne


Why not go directly to the source? The Ruby Language Specification couldn't be more clear and obvious (emphasis added by me):

6.2 Variables

6.2.1 General description

A variable is denoted by a name, and refers to an object, which is called the value of the variable. A variable itself is not an object.

like image 43
Jörg W Mittag Avatar answered Oct 20 '22 21:10

Jörg W Mittag