#to_b - why isn't this one already in there?

L

Lloyd Linklater

Phlip said:
Puh-leeze. "Binary" is soo Last Millenium.

If we are going for really cool new tech, how about

/set bugs OFF

or even a

require 'do_what_i_mean

p.s. I know I left off the closing single quote, but it knows what I
mean.
 
R

Robert Klemme

2007/9/10 said:
If we are going for really cool new tech, how about

/set bugs OFF

or even a

require 'do_what_i_mean

p.s. I know I left off the closing single quote, but it knows what I
mean.

... but only after successful requiring, so you actually *have* to
properly close the quote. :)

robert
 
T

Trans

This makes more sense as #to_bool, and certainly not default
conditional behavior. Yet, a #to_b to dictate conditions could be
useful, allowing us to create our own variants of Nil. However, the
only alternate to Nil I've ever found useful is Null (nil that returns
itself on method_missing) --so I'd be pretty happy if we just had
that. Also, I believe there's a efficiency issue with using #to_b for
conditions, which is why it is never considered.

Sorry, I momentarily had gotten the convention backward. You are
right, #to_b is the correct method, not #to_bool. #to_bool would make
sense for effecting conditionals though, not #to_b.

T.
 
S

Sharon Rosner

everybody knows

if "false"

returns true.

class Object
def to_bool
case self
when true, false: self
when nil: false
else
to_i != 0
end
end
end

class String
TRUE_REGEXP = /^(yes|true|on|t|1|\-1)$/i.freeze
FALSE_REGEXP = /^(no|false|off|f|0)$/i.freeze

def to_bool
case self
when TRUE_REGEXP: true
when FALSE_REGEXP: false
else
to_i != 0
end
end
end

"false".to_bool #=> false
"on".to_bool #=> true
1.to_bool #=> true
0.to_bool #=> false
"1".to_bool #=> true
nil.to_bool #=> false

enjoy
Sharon
 
T

Trans

class Object
def to_bool
case self
when true, false: self
when nil: false
else
to_i != 0
end
end
end

class String
TRUE_REGEXP = /^(yes|true|on|t|1|\-1)$/i.freeze
FALSE_REGEXP = /^(no|false|off|f|0)$/i.freeze

def to_bool
case self
when TRUE_REGEXP: true
when FALSE_REGEXP: false
else
to_i != 0
end
end
end

Ah. This is a good example for demonstrating what I meant. To fit into
Ruby convention, only TrueClass, FalseClass and NilClass (and things
like NullClass) should respond to to_bool. The String method should be
#to_b, because it is not a true "Boolean" type.

T.
 

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

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top