Quick: it responds, it evaluates, and is not empty

quick quest: anyone know of a nice slick short and sweet way to do this:

if self.respond_to?(:ameth)
	if ameth
		if not ameth.to_s.empty?
			...
		end
	end
end
···


tom sawyer, aka transami
transami@transami.net

                               .''.
   .''.      .        *''*    :_\/_:     .
  :_\/_:   _\(/_  .:.*_\/_*   : /\ :  .'.:.'.

.’’.: /\ : ./)\ ‘:’* /\ * : ‘…’. -=:o:=-
:/:’.:::. | ’ ‘’ * ‘.’/.’ (/’.’:’.’
: /\ : ::::: = / -= o =- /)\ ’ *
’…’ ‘:::’ === * /\ * .’/.’. ‘._____
* | : |. |’ .—"|
* | _ .–’| || | _| |
* | .-’| __ | | | || |
.-----. | |’ | || | | | | | || |
__’ ’ /"\ | '-."". ‘-’ ‘-.’ '` |.

i’m assuming :ameth and ameth are meant to be a Symbol and String
respectively, otherwise the 2nd and 3rd calls would be meaningless since the
call to respond_to? would have failed so

respond_to? :ameth and ameth and not ameth.to_s.empty? …

short ciruits the same way. not that short… but potentially one line.

it’s hard to envision why simply

… if respond_to ameth

would not suffice though? why have :ameth and ameth?

-a

···

On Fri, 17 Jan 2003, Tom Sawyer wrote:

quick quest: anyone know of a nice slick short and sweet way to do this:

if self.respond_to?(:ameth)
if ameth
if not ameth.to_s.empty?

end
end
end

====================================

Ara Howard
NOAA Forecast Systems Laboratory
Information and Technology Services
Data Systems Group
R/FST 325 Broadway
Boulder, CO 80305-3328
Email: ahoward@fsl.noaa.gov
Phone: 303-497-7238
Fax: 303-497-7259
====================================

Hi –

quick quest: anyone know of a nice slick short and sweet way to do this:

if self.respond_to?(:ameth)
if ameth
if not ameth.to_s.empty?

end
end
end

I think it’s probably worth having a temp variable here to avoid
calling the method an extra time:

if respond_to?(:ameth)
if (a = self.ameth)
unless a.to_s.empty?

end
end
end

or Boolean operator-wise (see other reply):

if respond_to?(:ameth) && (a = self.ameth) &&! (a.to_s.empty?)

end

or some combination.

I continue to dislike the repetition of the

if obj.respond_to?(:meth) then obj.meth …

thing, although I don’t know how to circumvent it efficiently and
effectively.

David

···

On Fri, 17 Jan 2003, Tom Sawyer wrote:


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav

Hello Tom,

Friday, January 17, 2003, 3:08:22 AM, you wrote:

quick quest: anyone know of a nice slick short and sweet way to do this:

    if self.respond_to?(:ameth)
            if ameth
                    if not ameth.to_s.empty?
                            ...
                    end
            end
    end

((not ameth.to_s.empty?) and …) rescue 0

···


Best regards,
Bulat mailto:bulatz@integ.ru

Hi –

quick quest: anyone know of a nice slick short and sweet way to do this:

if self.respond_to?(:ameth)
  if ameth
  	if not ameth.to_s.empty?
  		...
  	end
  end
end

i’m assuming :ameth and ameth are meant to be a Symbol and String
respectively, otherwise the 2nd and 3rd calls would be meaningless since the
call to respond_to? would have failed so

respond_to? :ameth and ameth and not ameth.to_s.empty? …

short ciruits the same way. not that short… but potentially one line.

it’s hard to envision why simply

… if respond_to ameth

would not suffice though? why have :ameth and ameth?

Because if you just have respond_to?(ameth), then ameth will
be evaluated (method call or local variable), which probably
isn’t what’s wanted.

irb(main):005:0> “”.respond_to?(:blah)
false
irb(main):006:0> “”.respond_to?(blah)
NameError: undefined local variable or method `blah’ for
#Object:0x401ccce0 from (irb):6

David

···

On Fri, 17 Jan 2003, ahoward wrote:

On Fri, 17 Jan 2003, Tom Sawyer wrote:


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav

begin
obj.meth
rescue NameError
“Well, I guess we’re stuffed, then.”
end

I remember you doing this in dbdbd, and I thought it was quite
elegant. I used it once to handle a nil argument in place of
something that responds to :to_h

hash =
begin
arg.to_h
rescue NameError
{}
end

I wanted to do

hash = arg.to_h rescue {}

but that doesn’t work.

Gavin

···

On Friday, January 17, 2003, 12:35:32 PM, dblack wrote:

I continue to dislike the repetition of the

if obj.respond_to?(:meth) then obj.meth …

thing, although I don’t know how to circumvent it efficiently and
effectively.

thanks, this seems the most concise answer, although i hesitate to use rescue.
is it exceedingly slow to do so?

···

On Thursday 16 January 2003 11:25 pm, Bulat Ziganshin wrote:

Hello Tom,

Friday, January 17, 2003, 3:08:22 AM, you wrote:

quick quest: anyone know of a nice slick short and sweet way to do
this:

    if self.respond_to?(:ameth)
            if ameth
                    if not ameth.to_s.empty?
                            ...
                    end
            end
    end

((not ameth.to_s.empty?) and …) rescue 0


tom sawyer, aka transami
transami@transami.net

                               .''.
   .''.      .        *''*    :_\/_:     .
  :_\/_:   _\(/_  .:.*_\/_*   : /\ :  .'.:.'.

.‘’.: /\ : ./)\ ‘:’* /\ * : ‘…’. -=:o:=-
:/:‘.:::. | ’ ‘’ * ‘.'/.’ (/’.‘:’.’
: /\ : ::::: = / -= o =- /)\ ’ *
‘…’ ‘:::’ === * /\ * .‘/.'. ‘._____
* | : |. |’ .—"|
* | _ .–’| || | _| |
* | .-‘| __ | | | || |
.-----. | |’ | || | | | | | || |
__’ ’ /“\ | '-.”". ‘-’ ‘-.’ '` |.

Hi –

I continue to dislike the repetition of the

if obj.respond_to?(:meth) then obj.meth …

thing, although I don’t know how to circumvent it efficiently and
effectively.

begin
obj.meth
rescue NameError
“Well, I guess we’re stuffed, then.”
end

I remember you doing this in dbdbd, and I thought it was quite
elegant.

I do actually like that construct – it’s just kind of (comparatively)
slow. Maybe my impression of its slowness is exaggerated by the fact
that my first use of it was in an XML-processing loop, and the
slow-down was quite noticeable.

I’ve actually been thinking about whether one could plausibly
implement a sort of “NACK” response (i.e., lack of response) from an
object, which would be neither nil nor false nor an exception, but
which would happen in the course of the method being called:

case self.some_meth
when /y/ …
when /n/ …
when nil …
when nack …
end

I used it once to handle a nil argument in place of
something that responds to :to_h

hash =
begin
arg.to_h
rescue NameError
{}
end

I wanted to do

hash = arg.to_h rescue {}

but that doesn’t work.

It does in 1.8.0preview1:

$ ruby -ve ‘h = “”.to_h rescue {}; p h’
ruby 1.8.0 (2002-12-24) [i686-linux]
{}

which is cool.

David

···

On Fri, 17 Jan 2003, Gavin Sinclair wrote:

On Friday, January 17, 2003, 12:35:32 PM, dblack wrote:


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav

Hello Gavin,

Friday, January 17, 2003, 5:31:37 AM, you wrote:

I wanted to do
hash = arg.to_h rescue {}
but that doesn’t work.

try

hash = (arg.to_h rescue {})

at least

a = 1
a = 0/0 rescue 0
p a #=> 0

in ruby 1.7.3 (2002-12-16) [i386-mswin32]

···


Best regards,
Bulat mailto:bulatz@integ.ru

Hello Tom,

Friday, January 17, 2003, 4:50:43 PM, you wrote:

((not ameth.to_s.empty?) and …) rescue 0

thanks, this seems the most concise answer, although i hesitate to use rescue.
is it exceedingly slow to do so?

i dont know. on the my side, i like ‘when NACK’ idea - may be because
it is close to pattern matching (in functional programming). in one
program i used 3rd variant, smth like:

def f(arr) # arr may be Array or nil
arr.flatten.size || 0
end

class NilClass
def flatten
nil
end
def size
nil
end
end

···


Best regards,
Bulat mailto:bulatz@integ.ru

Hi –

···

On Fri, 17 Jan 2003, Tom Sawyer wrote:

On Thursday 16 January 2003 11:25 pm, Bulat Ziganshin wrote:

((not ameth.to_s.empty?) and …) rescue 0

thanks, this seems the most concise answer

However, it doesn’t do what you originally were doing. false.to_s is
“false” (not an empty string), so only testing ameth.to_s.empty? is
not the same as testing ameth for truth separately from testing
ameth.to_s for emptiness.

David


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav

now that is a very interesting idea. NACK as in Not ACKnowledged, yes? reminds
me a little of javascripts NaN and undefined. but something like this would
be so much more useful in Ruby --so much cleaner than having to use
respond_to? but this would cause one major change in Ruby’s current behavior.
NACK methods would not raise an error.

···

On Thursday 16 January 2003 07:41 pm, dblack@candle.superlink.net wrote:

I’ve actually been thinking about whether one could plausibly
implement a sort of “NACK” response (i.e., lack of response) from an
object, which would be neither nil nor false nor an exception, but
which would happen in the course of the method being called:

case self.some_meth
when /y/ …
when /n/ …
when nil …
when nack …
end


tom sawyer, aka transami
transami@transami.net

                               .''.
   .''.      .        *''*    :_\/_:     .
  :_\/_:   _\(/_  .:.*_\/_*   : /\ :  .'.:.'.

.‘’.: /\ : ./)\ ‘:’* /\ * : ‘…’. -=:o:=-
:/:‘.:::. | ’ ‘’ * ‘.'/.’ (/’.‘:’.’
: /\ : ::::: = / -= o =- /)\ ’ *
‘…’ ‘:::’ === * /\ * .‘/.'. ‘._____
* | : |. |’ .—"|
* | _ .–’| || | _| |
* | .-‘| __ | | | || |
.-----. | |’ | || | | | | | || |
__’ ’ /“\ | '-.”". ‘-’ ‘-.’ '` |.

i dont know. on the my side, i like ‘when NACK’ idea - may be because
it is close to pattern matching (in functional programming). in one
program i used 3rd variant, smth like:

i agree, nack would be good. i suppose returning nil if the method doesn’t
exist is out of the question?

def f(arr) # arr may be Array or nil
arr.flatten.size || 0
end

class NilClass
def flatten
nil
end
def size
nil
end
end

ah, yes, you know i already have added a to_s method to the NilClass to ease
things on that end. hmmm…you gave me an idea. perhaps this:

x is a symbol

def has_value?(x)
return nil if not self.respond_to?(x)
case send(x)
when nil, false, 0, 0.0, ‘’, , {}
return false
else
return true
end
end

but where would it go? Kernel?

···

On Friday 17 January 2003 07:08 am, Bulat Ziganshin wrote:


tom sawyer, aka transami
transami@transami.net

Hi –

···

On Fri, 17 Jan 2003 dblack@candle.superlink.net wrote:

Hi –

On Fri, 17 Jan 2003, Tom Sawyer wrote:

On Thursday 16 January 2003 11:25 pm, Bulat Ziganshin wrote:

((not ameth.to_s.empty?) and …) rescue 0

thanks, this seems the most concise answer

However, it doesn’t do what you originally were doing. false.to_s is
“false” (not an empty string), so only testing ameth.to_s.empty? is
not the same as testing ameth for truth separately from testing
ameth.to_s for emptiness.

I should add: it also doesn’t duplicate the respond_to? functionality,
because an exception might be raised by something other than there
beign no ameth method (such as division by zero in #ameth).

David


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav

dblack@candle.superlink.net wrote:

I’ve actually been thinking about whether one could plausibly
implement a sort of “NACK” response (i.e., lack of response) from an
object, which would be neither nil nor false nor an exception, but
which would happen in the course of the method being called:

A quick hack would be to have a NackClass, mix in Singleton, and have a
global variable $nack pointing to the instance. Then have a
method_missing returning $nack for every class you want to exhibit the
behaviour.

Now if only method_missing called super by default we could just have
this as a mixin to object. Though it would still conflict with any other
Object#method_missing anyone wanted to write.

martin

Not at all!

class Object
def method_missing(*hey_who_needs_arguments)
nil
end
end

Gavin

···

On Saturday, January 18, 2003, 1:22:09 AM, Tom wrote:

i dont know. on the my side, i like ‘when NACK’ idea - may be because
it is close to pattern matching (in functional programming). in one
program i used 3rd variant, smth like:

i agree, nack would be good. i suppose returning nil if the method doesn’t
exist is out of the question?

David, the subtilties you pervade.

···

On Friday 17 January 2003 07:41 am, dblack@candle.superlink.net wrote:

I should add: it also doesn’t duplicate the respond_to? functionality,
because an exception might be raised by something other than there
beign no ameth method (such as division by zero in #ameth).


tom sawyer, aka transami
transami@transami.net

                               .''.
   .''.      .        *''*    :_\/_:     .
  :_\/_:   _\(/_  .:.*_\/_*   : /\ :  .'.:.'.

.‘’.: /\ : ./)\ ‘:’* /\ * : ‘…’. -=:o:=-
:/:‘.:::. | ’ ‘’ * ‘.'/.’ (/’.‘:’.’
: /\ : ::::: = / -= o =- /)\ ’ *
‘…’ ‘:::’ === * /\ * .‘/.'. ‘._____
* | : |. |’ .—"|
* | _ .–’| || | _| |
* | .-‘| __ | | | || |
.-----. | |’ | || | | | | | || |
__’ ’ /“\ | '-.”". ‘-’ ‘-.’ '` |.

Hello Tom,

Friday, January 17, 2003, 5:22:09 PM, you wrote:

i dont know. on the my side, i like ‘when NACK’ idea - may be because
it is close to pattern matching (in functional programming). in one
program i used 3rd variant, smth like:

i agree, nack would be good. i suppose returning nil if the method doesn’t
exist is out of the question?

i don’t inderstand your thought. btw, we can ask for syntax like:

EXPRESSION except DEFAULT VALUE

which returns default value when any method DIRECTLY called in expression
is not exist (ie, it will be syntax sugar for checking like your original post)

···


Best regards,
Bulat mailto:bulatz@integ.ru

Hi –

···

On Fri, 17 Jan 2003, Gavin Sinclair wrote:

On Saturday, January 18, 2003, 1:22:09 AM, Tom wrote:

i dont know. on the my side, i like ‘when NACK’ idea - may be because
it is close to pattern matching (in functional programming). in one
program i used 3rd variant, smth like:

i agree, nack would be good. i suppose returning nil if the method doesn’t
exist is out of the question?

Not at all!

class Object
def method_missing(*hey_who_needs_arguments)
nil
end
end

It can be done, but it’s not a general solution, because there might
be methods that do exist and still return nil. Thus a nil return
can’t be treated as an unambiguous synonym for not responding.

David


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav

why not add a new return value to Object::respond_to? ?

eg:

case o.respond_to? :sym
when true
# o responds to this
when false
# o does not respond to this
when nil
# o does not acknowldedge this (NACK)
end

i believe this would maintain backwards compatibility since old code would not
distinguish between false/nil returns from respond_to? but would allow new
code to have the concept of NACK without any new classes or globals required.

can someone give me a simple example of wanting a NACK though? i think this
thread has ignored the original question of how to :

if self.respond_to?(:ameth)
if ameth
if not ameth.to_s.empty?

end
end
end

which to me seems to read “if i respond to a symbol known at compile time
then eval ameth a couple of times, where ameth may be a method call or local
varibable but i don’t really care which, and iff ameth returned anything other
than ‘’ then do …” or something pretty close to this. this seems really
from the hip : assuming this is some pretty dynamic code, wouldn’t you have
some idea, based on what is in ameth, what to do with it more strongly
correlated to reality than whether or not self responds to the compile time
symbol :ameth? i think if the purpose of the above logic were explained and
answer may arise not involving NACK at all…

-a

···

On Fri, 17 Jan 2003 dblack@candle.superlink.net wrote:

It can be done, but it’s not a general solution, because there might
be methods that do exist and still return nil. Thus a nil return
can’t be treated as an unambiguous synonym for not responding.

====================================

Ara Howard
NOAA Forecast Systems Laboratory
Information and Technology Services
Data Systems Group
R/FST 325 Broadway
Boulder, CO 80305-3328
Email: ahoward@fsl.noaa.gov
Phone: 303-497-7238
Fax: 303-497-7259
====================================