tags:

views:

93

answers:

3

Hello,

I was writing a small Heap implementation and upon creating my Node class I noticed some weird behaviour. I wanted to call defined?(x) to ensure x was defined, then check if x was an Integer, before storing it in the Node's value class variable. In IRB I can call defined?(x) and the result is nil.

However, in the class, I try this:

def change_value value
  @value = value if defined?(value)
end

and the result when I call the change_value with a random letter, let's say 'e', is the standard undefined local variable or method error. Again, in IRB it seems to work fine and I am wondering if I have some kind of environment issue or if this is not the 'best' way to check if value is really there.

Thanks.

A: 

Would it have to do with calling the method from the class instance and not the object instance?

JRL
+1  A: 

This isn't the best way to check if it's really there. If change_value is called without providing any parameters, you would get:

ArgumentError: wrong number of arguments (0 for 1)

Instead, you might want to check to make sure value is not nil. Of course you can do this a variety of ways:

if !value.nil?
  #...
end

if value
  # this will be exeuted if value is either not `nil` or not `false`
end

Best of luck!

nicholaides
+7  A: 

(Edit: DigitalRoss has since cleaned up the question's formatting, so the comment on formatting and the initial re-write may no longer apply. I'll leave them in until I get some feedback from the OP.)

That's a nearly unreadable way to write a method and it doesn't even parse on my machine (Ruby 1.8.7).

I'm assuming you mean the following:

def change_value(value)
  @value = value if defined?(value)
end

This works fine when I call it, but it's incorrect. nil and undefined are two different beasts in Ruby; value will always be defined in that context because it's a declared method parameter. I suspect what you are really after is:

def change_value(value)
  @value = value unless value.nil?
end

Note that some people would simply write this as:

def change_value(value)
  @value = value if value
end

because nil is "falsy". However, this form conflates nil and false, so it's not a good habit to get into.

Avdi
+1 for the last example.
Simone Carletti