nil.to_i returning zero

  • Thread starter Gerardo Santana Gómez Garrido
  • Start date
R

Rick DeNatale

Reasonable choice I have to admit ;)


ok that was actually what I wanted you hear saying ;)
But how would you implement
a +=1 for a being nil?


Been there, done that <G>

From two days ago:
class NilClass

def +(aNumber)
aNumber
end

def -(aNumber)
0 - aNumber
end
...
 
R

Robert Dober

Am 17 Oct 2007 um 16:31 hat Robert Dober geschrieben:


I think this is a reasonable proposal:

class NilClass
def +(obj)
obj
end
end

Can you think of any case in which this poses a problem?
Hmm, let me see
a = [42]
b += a
b << [43] ouch that hurts

maybe
class NilClass
def + obj
obj.clone rescue obj
end
end
Cheers
Robert
 
D

Dirk Traulsen

Am 17 Oct 2007 um 21:08 hat Robert Dober geschrieben:
I think this is a reasonable proposal:

class NilClass
def +(obj)
obj
end
end

Can you think of any case in which this poses a problem?

Hmm, let me see
a = [42]
b += a
b << [43] ouch that hurts

maybe
class NilClass
def + obj
obj.clone rescue obj
end
end

You're right. That's really better.
(You didn't have to look too hard for a problem, did you? :) Sometimes
I'm blind! )

But in earnest, I really think this would be a good thing to have in
Ruby.

I'm not so sure about the other cases *,- and /. There you would have
to make a not so short list of object classes for which they must be
handled differently.

But not for +, there it is very clear:
nothing + x is always x, independant from the nature of x.

So, as this is universally correct, it could go in Ruby itself.
 
D

David A. Black

Hi --

nil is an interesting beast. In one of my projects, I added "each" to
NilClass

class NilClass
def each
end
end

so that I can treat nil returned from IO:select as if it is an empty array.

I like this change personally, and it does make sense to me logically
("doing something on each element of nothing" is equivalent to "do
nothing"),
but does it make sense to everybody? What if somebody fail to capture the
bug
because of this change?

I would definitely not make a change like that. First of all, nil
isn't composed of elements, so there's no concept of "each element" of
nil. Second, the answer to your second question is: the program will
almost certainly blow up or silently do something it isn't supposed to
do. That's what happens when you mask bugs :) It's not a good idea.


David

--
Upcoming training from Ruby Power and Light, LLC:
* Intro to Ruby on Rails, Edison, NJ, October 23-26
* Advancing with Rails, Edison, NJ, November 6-9
Both taught by David A. Black.
See http://www.rubypal.com for more info!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,269
Messages
2,571,349
Members
48,028
Latest member
Rigor4

Latest Threads

Top