Everything is a object?

Hello,

I understood everything is a object, and the base class for all objects
is object :slight_smile:

so when I try to write just that this line below in my code i get an
error?

puts just_something.class.to_s

undefined local variable or method 'just_something' for main:object

why does this happend?

I cannot even write this below

puts 'nil' unless just_something.nil?

hope someone can help me understand whats wrong :slight_smile:

Thanks :smiley:

Jamal

···

--
Posted via http://www.ruby-forum.com/.

Basically, everything *that exists* in Ruby is an object. If it doesn't
exist yet, it can't be an object. You have to have a "just_something"
before it can be an object. You could try creating a "just_something"
with an assignment, for instance:

  irb(main):001:0> just_something = 0
  => 0
  irb(main):002:0> puts just_something.class.to_s
  Fixnum
  => nil

···

On Wed, Apr 04, 2007 at 07:49:05AM +0900, Jamal Soueidan wrote:

I understood everything is a object, and the base class for all objects
is object :slight_smile:

so when I try to write just that this line below in my code i get an
error?

puts just_something.class.to_s

undefined local variable or method 'just_something' for main:object

why does this happend?

I cannot even write this below

puts 'nil' unless just_something.nil?

hope someone can help me understand whats wrong :slight_smile:

--
CCD CopyWrite Chad Perrin [ http://ccd.apotheon.org ]

It has been long topic now, and very helpful, I must admit I really love
the Ruby Community, such Community is hard to find other places :slight_smile:

I want to thanks everyone very much :slight_smile:

···

------------------------------------------

I think now I understand completely why the following code below is
throwing exception:

puts myvar
# register.rb:1: undefined local variable or method 'myvar' for
main:Object

Ruby don't know what "myvar" is, it could not find any local variable
with that name, or any method in the main:Object (base class)

------------------------------------------

The code below would not throw any exception:
puts @myvar
# nil

Ruby already know whatever start with @ would be instance of something,
if not then it would still be nil object, means false.

puts @myvar.class.to_s
# NilClass

puts @myvar="string".class.to_s
# String

---------------------

The Accessors only provide you with the set and get properties similar
to other languages, when you declare something like this:

attr_accessor :myvar

You would have an instance of nil object.

class A
   attr_accessor :myvar
end

a = A.new
p a.myvar.class.to_s
# NilClass

p a.myvar=2.class.to_s
# Fixnum

p a.myvar='string'.class.to_s
# String

---------------------

Why does Ruby treat @myvar different from myvar?

Posted by unknown (Guest) on 04.04.2007 15:30
Exactly why it does that with instance variables and not with local variables
I don't know, but they are used in different enough ways that the difference
should not be bothersome.

The answer:

Posted by Brian Candler (Guest) on 04.04.2007 15:44
That's because both method names and local variable names fall into the same name space

---------------------

I thank again everyone :smiley:

My sister just asked me today "Who is Ruby, is she your girlfriend?" LOL

--
Posted via http://www.ruby-forum.com/\.

Chad Perrin wrote:

···

On Wed, Apr 04, 2007 at 07:49:05AM +0900, Jamal Soueidan wrote:

why does this happend?

I cannot even write this below

puts 'nil' unless just_something.nil?

hope someone can help me understand whats wrong :slight_smile:

Basically, everything *that exists* in Ruby is an object. If it doesn't
exist yet, it can't be an object. You have to have a "just_something"
before it can be an object. You could try creating a "just_something"
with an assignment, for instance:

  irb(main):001:0> just_something = 0
  => 0
  irb(main):002:0> puts just_something.class.to_s
  Fixnum
  => nil

how can I check if its not a object because then its empty and not
created ?

--
Posted via http://www.ruby-forum.com/\.

It has been long topic now, and very helpful, I must admit I really love
the Ruby Community, such Community is hard to find other places :slight_smile:

I want to thanks everyone very much :slight_smile:

It looks like things are a lot clearer for you now. Just a couple
comments on your summary:

The code below would not throw any exception:
puts @myvar
# nil

Ruby already know whatever start with @ would be instance of something,
if not then it would still be nil object, means false.

Start a brand new session of IRB and try:

instance_variables

=>

@alpha

=> nil

instance_variables

=> ["@alpha"]

@beta = 42

=> 42

instance_variables

=> ["@alpha", "@beta"]

instance_variable_set("@gamma", 'foo')

=> "foo"

instance_variables

=> ["@alpha", "@beta", "@gamma"]

Instance variables come into existence when
   1) they appear on the left side of an assignment, in which case they are
      initialized to the value on the right hand side of the assignment
   2) when they are referenced in an expression, in which case they are
      initialized with a reference to the nil object.
   3) when they are set via a call to instance_variable_set()

The Accessors only provide you with the set and get properties similar
to other languages, when you declare something like this:
attr_accessor :myvar
You would have an instance of nil object.

This is a bit misleading. There is one and *only* one instance of NilClass.
So it would be better to say:

   You would have a reference to *the* nil object, which is an instance
   of NilClass (the *only* instance).

All reference to 'nil' are references to the *same* object:

@a # force @a to exist
@b # force @b to exist

@a.object_id # 4
@b.object_id # 4
nil.object_id # 4

@a.equal?(nil) # true
@b.equal?(nil) # true
nil.equal?(nil) # true

I think the key thing to remember is that 'nil' is not a special value that
indicates 'no object'. Instead it is a special object that acts as a sentinel.
There are a number of Ruby conventions that allow nil to act as a powerful and
useful sentinel:

    1) instance variables and global variables default to reference the nil object.
    2) The literal 'nil' always references the same object, the nil object.
    3) There is no way to create additional instances of NilClass.
    4) All objects respond to the method: 'nil?'
    5) The nil object is the *only* object that responds with 'true' to 'nil?'.
       All other objects respond with 'false'.
    6) In a boolean context, 'nil' is considered false.

These properties enable such idioms as:

    @foo ||= 'default'
    @bar = first_choice || second_choice || third_choice

Ruby's dynamic typing allows 'nil' to be used as a convenient sentinel value for
many methods. For example 'getc' returns the next byte from an IO stream as
an instance of Fixnum but if the end of the stream is encountered nil is returned
instead of a special sentinel instance of Fixnum (e.g. -1 as in the C programming
language).

Gary Wright

···

On Apr 4, 2007, at 2:49 PM, Jamal Soueidan wrote:

puts @myvar.class.to_s
# NilClass

puts does an implicit to_s on anything you pass to it, so you don't actually
need to do that explicitly.

puts @myvar="string".class.to_s
# String

Careful here. This is the same as

  puts @myvar=("string".class.to_s)

i.e. you are assigning "String" to @myvar, not "string".

p a.myvar=2.class.to_s
# Fixnum

Again, here the @myvar instance variable of 'a' now contains string "Fixnum"

Regards,

Brian.

···

On Thu, Apr 05, 2007 at 03:49:15AM +0900, Jamal Soueidan wrote:

how can I check if its not a object because then its empty and not
created ?

If it's empty that means it has been created but with a nil value. You
have to check if its defined in the current scope:

irb(main):005:0> defined? a
=> nil
irb(main):006:0> a
NameError: undefined local variable or method `a' for main:Object
        from (irb):6

···

Jamal Soueidan <jkhaledsoueidan@gmail.com> wrote:
        from :0

--
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand
something when his salary depends on not
understanding it" - Upton Sinclair

Jamal Soueidan wrote:

Thanks :smiley:

defined?

which class have that method?

I cannot find it in the documentation page?

···

--
Posted via http://www.ruby-forum.com/\.

Gary Wright wrote:

Thanks for your comment, now I understand that all the unused instance
variable would reference to the same object until they come into
existence:

1. by assigement.
2. by reference (as default to nil object)
3. by using the object method instance_variable_set()

Brian Candler wrote:

puts does an implicit to_s on anything you pass to it, so you don't actually
need to do that explicitly.

Thanks, now I know :slight_smile:

puts @myvar="string".class.to_s
# String

Careful here. This is the same as

  puts @myvar=("string".class.to_s)

True,
puts "string".class

···

On Apr 4, 2007, at 2:49 PM, Jamal Soueidan wrote:
On Thu, Apr 05, 2007 at 03:49:15AM +0900, Jamal Soueidan wrote:

-----------------------------------------

Thanks for the other replies :smiley:

Now the question is,

When does the instance variable holds the object itself?

class A; end;

@one = A.new
@two = A.new

p @one.object_id
p @one_object_id
# 21103660
# 21103640

Two different objects, even if they were the same.

How does all the nil instance variable reference to the same object?

--
Posted via http://www.ruby-forum.com/\.

Start a brand new session of IRB and try:

> instance_variables
=>
> @alpha
=> nil
> instance_variables
=> ["@alpha"]
> @beta = 42
=> 42
> instance_variables
=> ["@alpha", "@beta"]
> instance_variable_set("@gamma", 'foo')
=> "foo"
> instance_variables
=> ["@alpha", "@beta", "@gamma"]

Not quite:irb(main):001:0> instance_variables
=>
irb(main):002:0> @alpha
=> nil
irb(main):003:0> instance_variables
=>
irb(main):004:0> @beta = 42
=> 42
irb(main):005:0> instance_variables
=> ["@beta"]
irb(main):006:0> defined? @alpha
=> nil
irb(main):007:0> defined? @beta
=> "instance-variable"

Instance variables come into existence when
   1) they appear on the left side of an assignment, in which case
they are
      initialized to the value on the right hand side of the assignment

Yes

   2) when they are referenced in an expression, in which case they are
      initialized with a reference to the nil object.

No, they are not initialized (or even defined) at this point. They
just evaluate syntactically to nil. See line 6 above.

   3) when they are set via a call to instance_variable_set()

Yes.

Note that the result of the defined? operator is a syntactic
description of the argument.

In line 6 above defined? @alpha is not saying that the value of
@alpha is nil, but that since it @alpha isn't defined, there's no
description, and since nil is treated as false in Ruby logical
expressions and anything other than nil and false is treated as true
you can do things like
  p @alpha if defined? @alpha

Here's another subtlety:
irb(main):008:0> defined? nil
=> "nil"

Note that it's not returning the value nil, but the descriptive string "nil".

From the ruby 1.8.5 source, the values which defined? can return are
"assignment", "class variable", "constant", "expression",
"global-variable", "instance-variable", "local-variable",
"local-variable(in-block)", "false", "method", "self", "super",
"true", "yield", and nil

It can also return things like "$1", "$2" etc. and "$$", "$`", "$/",
"$'", and "$+" for regexp match references. These are only defined
after a regexp match which sets them, until a regexp match which
doesn't.

···

On 4/4/07, Gary Wright <gwtmp01@mac.com> wrote:

--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

It is a language keyword, not a method, so you won't
find it in any of the class documentation. You'll have
to look at one of the language manuals. It is
discussed here:

http://www.rubycentral.com/book/tut_expressions.html

I'm not sure If that is a helpful direction for you
though based on your previous questions.

It seems like you try working with some of the
tutorials. There are some good links for getting
started with Ruby at:

http://www.ruby-lang.org/en/documentation/

Gary Wright

···

On Apr 3, 2007, at 8:09 PM, Jamal Soueidan wrote:

Jamal Soueidan wrote:

Thanks :smiley:

defined?

When does the instance variable holds the object itself?

Instance variables never hold the objects themselves.
Ruby variables always hold references to objects.

Note: It is often explained that in some special cases
Ruby variables hold 'immediate values'. Such as small
integers as Fixnum instances and the unique objects
nil, false, and true. I think that this is an
unnecessary complication. It is easier and more
consistent to always talk about references. In
particular assignment is always about copying a
reference and *never* about duplicating an object
or a value:

a = 1 # 1 is a reference to a Fixnum
             # now a references the same fixnum
b = a # b now references the same fixnum as a

a = "foo" # a is a reference to a string instance
b = a # b now references the same string as a

The 'trick' is to think of literals (-1,0,1,nil,true,false, etc.)
as references and *not* as values or objects.

I'd almost go as far to say that in Ruby there is only
one type of value, an object reference. Assignment, method
argument passing and return values are all about the copying
of references and not at all about objects.

class A; end;

@one = A.new
@two = A.new

p @one.object_id
p @one_object_id
# 21103660
# 21103640

Two different objects, even if they were the same.

Do you have a typo there? Do you want:

   p @one.object_id
   p @two.object_id

These are two different objects and so they have two
different object ids. I'm not sure what your question
is here.

How does all the nil instance variable reference to the same object?

Can you rephrase the question? I'm not sure what you are asking.

@a = nil
@b = @a
@c = @b

All three instance variables now reference the same object. It
is the same object referenced by the literal, nil. Don't think
of 'nil' as an object. Think of it as a reference to a particular
distinguished object.

···

On Apr 6, 2007, at 9:24 AM, Jamal Soueidan wrote:

Thanks for the correction. I could have sworn that I tested that code
before posting to make sure I understood what was going on. Maybe I
had some left over variables from earlier in the irb session.

So it is *only* assignment and instance_variable_set that will cause
an instance variable to become defined and bound to a reference.

Undefined instance variables evaluate to nil.

Gary Wright

···

On Apr 6, 2007, at 2:24 PM, Rick DeNatale wrote:

   2) when they are referenced in an expression, in which case they are
      initialized with a reference to the nil object.

No, they are not initialized (or even defined) at this point. They
just evaluate syntactically to nil. See line 6 above.

Now the question is,

When does the instance variable holds the object itself?

Instance variables hold references to what ever object you assigned to them.

class A; end;

@one = A.new
@two = A.new

p @one.object_id
p @one_object_id
# 21103660
# 21103640

Two different objects, even if they were the same.

Perhaps you'd find it helpful if you tried to work out yourself what was
going on - and if you can't, explain your own explanation and why you think
it is wrong.

But to answer it for you:

(1) A.new generates a new instance of class A. Every time you invoke A.new
you get a fresh object. Each object has a unique object_id during its
lifetime.

(2) '@one = A.new' assigns (a reference to) the newly-created object into an
instance variable. Since this assignment is "out in the wild", i.e. not
inside any "class Foo .. end" or "def bar .. end" construct, then you are
assigning to an instance variable of a top-level session object called
'main'

A longer way of writing it would have been:

main.instance_variable_set(:@one, Foo.new)

Then assigning to @two you'll get another object reference stored there.

Clearly then, puts @one.object_id and puts @two.object_id will show you
distinct references to the two distinct objects you created.

Try also:

puts main.inspect
puts main.instance_variables

However unless you're just playing around in irb, nobody creates instance
variables inside 'main'. You normally create them within an object of your
own.

Brian.

···

On Fri, Apr 06, 2007 at 10:24:58PM +0900, Jamal Soueidan wrote:

Gary Wright wrote:

It is a language keyword, not a method, so you won't
find it in any of the class documentation. You'll have
to look at one of the language manuals. It is
discussed here:

Gary Wright

if (empty($var))

even if the $var is not declared..

I thought in Ruby it will work the same way

if var.empty? (but empty is only in the String) so I thought something
like this would solve it.

if var.to_s.empty? (object to string)

this didn't work either, but object had the nil method which could be
used :slight_smile:

if var.nil?

this didn't work either ..

so in Ruby everything is object if it was declared before :stuck_out_tongue: o

···

From my previous language (PHP) I could easily write function like this

--
Posted via http://www.ruby-forum.com/\.

Gary Wright wrote:

···

On Apr 6, 2007, at 9:24 AM, Jamal Soueidan wrote:

Two different objects, even if they were the same.

Do you have a typo there? Do you want:

   p @one.object_id
   p @two.object_id

I thought that if both @instance don't have the same object_id they
would two different objects...but that is not true?

--
Posted via http://www.ruby-forum.com/\.

If you want two separate names for the same object with the same object
ID (aka the same object_id), you could chain assignments together:

  irb(main):003:0> three = four = A.new
  => #<A:0x80566b4>
  irb(main):004:0> three.object_id === four.object_id
  => true
  irb(main):005:0> p three.object_id
  67285850
  => nil
  irb(main):006:0> p four.object_id
  67285850
  => nil

···

On Sat, Apr 07, 2007 at 06:23:50PM +0900, Brian Candler wrote:

On Fri, Apr 06, 2007 at 10:24:58PM +0900, Jamal Soueidan wrote:
> Now the question is,
>
> When does the instance variable holds the object itself?

Instance variables hold references to what ever object you assigned to them.

> class A; end;
>
> @one = A.new
> @two = A.new
>
> p @one.object_id
> p @one_object_id
> # 21103660
> # 21103640
>
> Two different objects, even if they were the same.

Perhaps you'd find it helpful if you tried to work out yourself what was
going on - and if you can't, explain your own explanation and why you think
it is wrong.

But to answer it for you:

(1) A.new generates a new instance of class A. Every time you invoke A.new
you get a fresh object. Each object has a unique object_id during its
lifetime.

(2) '@one = A.new' assigns (a reference to) the newly-created object into an
instance variable. Since this assignment is "out in the wild", i.e. not
inside any "class Foo .. end" or "def bar .. end" construct, then you are
assigning to an instance variable of a top-level session object called
'main'

A longer way of writing it would have been:

main.instance_variable_set(:@one, Foo.new)

Then assigning to @two you'll get another object reference stored there.

Clearly then, puts @one.object_id and puts @two.object_id will show you
distinct references to the two distinct objects you created.

--
CCD CopyWrite Chad Perrin [ http://ccd.apotheon.org ]
Leon Festinger: "A man with a conviction is a hard man to change. Tell
him you disagree and he turns away. Show him facts and figures and he
questions your sources. Appeal to logic and he fails to see your point."

From my previous language (PHP) I could easily write function like this

if (empty($var))

even if the $var is not declared..

I thought in Ruby it will work the same way

Ruby does not have an analogous concept to PHP's empty.

Ruby's 'defined?' is closer to PHP's 'isset' (for variables) or
'defined' (for constants).

You have to be careful with analogies between PHP and Ruby because
the languages don't treat variables, data and objects in the same
way at all. For example, PHP's function 'is_object(var)' is
superfluous in Ruby since if a variable is defined it must refer
to an object--there are no other 'things' that a variable can
reference. In PHP a basic string is *not* an object. Ruby does
not have that type of distinction.

The various tests for Ruby objects that would match PHP's empty
function:

         "".empty? # true for an empty string
         "x".empty? # false
         "0".empty? # false (strings aren't auto converted )
         "0".to_int.zero? # true

         0.zero? # true
         1.zero? # false

         nil.nil? # yes, nil is the nil object
         0.nil? # no, zero is not nil object

         x = false # make x refer to the false object
         x == false # true, x refers to the false object
         x == true # false, x doesn't refer to the false object
         x = true # x now refers to the false object
         x == false # false, x doesn't refer to the false object
         x == true # true, x does refer to the false object

         .empty? # true, the array is empty
         [100].empty? # false, the array is not empty

In a boolean context false and nil are the only objects that are
considered false. All other objects (0, an empty array, an empty
string) are considered true:

if x
   # x is neither nil nor false
else
   # x must be nil or false
end

If you really wanted to match PHP's empty function you would have to do
something like:

def empty(obj)
   [nil, 0, false, , "", "0"].include?(obj)
end

But that still won't work for variables that are not defined. In
practice the need to decide if a variable is defined or not is rare
though.

so in Ruby everything is object if it was declared before :stuck_out_tongue: o

As with most absolutes the phrase 'everything is an object' is only
true within a particular context. In this case with respect to
data. All data in Ruby is accessed and manipulated in the context
of objects and their methods. But variables are not data in Ruby.
Variables reference objects but aren't themselves objects. Other
parts of the language can be accessed and manipulated as objects
(data) though: classes, modules, methods, and more.

Gary Wright

···

On Apr 3, 2007, at 8:39 PM, Jamal Soueidan wrote:

Jamal Soueidan wrote:

so in Ruby everything is object if it was declared before :stuck_out_tongue: o

I think perhaps the more accurate, though less sexy, wording is "every expression that returns returns an object."*

For example: 'rescue' is not an object, it's a keyword. 'begin..rescue..end' is an expression, and hence has a return value, and that return value is an object.

In your case: 'as_yet_undefined_variable' is an expression, too. In the case of a bare word, Ruby's built-in behavior is to:
1) check for a local variable binding
2) failing that, send a message to self

#1 is failing, so it sends the as_yet_undefined_variable message to self. If the method were defined, it would invoke it. Since it's not defined, it calls method_missing on self.

This is all built-in, unoverrideable behavior (AFAIK).

The default implementation of method_missing (which you *can* override) raises a NoMethodError exception. The exception is an object, but the act of "raising" it triggers some built-in behavior to fail fast. This is why I say "every expression that returns" instead of "every expression". This is one case of an expression that doesn't return.

This is all more complicated than the cute "Everything is an object," but it's also far more useful, and in my opinion, pretty intuitive.**

I Might Be Wrong.

Of course, I'm guessing Gary's email is more useful to you, but I don't know PHP, and I'm a pedant.

Also, if you find yourself using defined? more than once a year, you might wanna post some code to ruby-talk for constructive criticism.***

Devin

* Lowercase 'o' intentional -- IIRC, evil.rb allows you to skirt the Object superclass thing.
** One exception being that you can't always say `puts a unless (a = some_method).nil?`. (Note the single equals sign, vice double.)
*** I'm including you, Rails Core!

Gary Wright wrote:

Two different objects, even if they were the same.

Do you have a typo there? Do you want:

   p @one.object_id
   p @two.object_id

I thought that if both @instance don't have the same object_id they
would two different objects...but that is not true?

That is true. All objects have unique object ids. If the objects
referenced by two variables have the same object id then you've got
two references to the same object.

In your original post you had:

@one = A.new
@two = A.new

p @one.object_id
p @one_object_id # TYPO???
# 21103660
# 21103640

Which just doesn't make sense. Specifically, @one_object_id isn't
defined in your example (note the underscore instead of dot)
and should have evaluated to nil. Since you illustrated two
different object_id's, I assumed you had simply made
some sort of cut and paste error and you had intended to show
@two.object_id and not @one_object_id.

···

On Apr 6, 2007, at 2:56 PM, Jamal Soueidan wrote:

On Apr 6, 2007, at 9:24 AM, Jamal Soueidan wrote: