[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Struct.new and symbol with question mark

Suraj Kurapati

11/7/2006 4:58:00 AM

Why isn't the Struct class smart enough to detect a question mark at the
end of a member name and create the appropriate #member= and #member?
methods?

>> Klass = Struct.new :foo, :bar?
=> Klass

>> x = Klass.new
=> #<struct Klass foo=nil, :bar?=nil>

>> x.foo
=> nil

>> x.bar?
NoMethodError: undefined method `bar?' for #<struct Klass foo=nil,
:bar?=nil>
from (irb):5
from :0

I was expecting Klass to have the #foo, #foo=, #bar?, and #bar= methods.

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

2 Answers

Morton Goldberg

11/7/2006 6:45:00 PM

0

On Nov 6, 2006, at 11:58 PM, Suraj Kurapati wrote:

> Why isn't the Struct class smart enough to detect a question mark
> at the
> end of a member name and create the appropriate #member= and #member?
> methods?
>
>>> Klass = Struct.new :foo, :bar?
> => Klass
>
>>> x = Klass.new
> => #<struct Klass foo=nil, :bar?=nil>
>
>>> x.foo
> => nil
>
>>> x.bar?
> NoMethodError: undefined method `bar?' for #<struct Klass foo=nil,
> :bar?=nil>
> from (irb):5
> from :0
>
> I was expecting Klass to have the #foo, #foo=, #bar?, and #bar=
> methods.

It doesn't work because :bar? isn't a valid symbol literal. The
follow does work:

<code>
#! /usr/bin/env ruby -w
Baz = Struct.new(:foo, :'bar?')
z = Baz.new(42, false)
z # => #<struct Baz foo=42, bar?=false>
z.bar? # => false
</code>

Regards, Morton



Daniel Berger

11/7/2006 7:21:00 PM

0

Suraj Kurapati wrote:
> Why isn't the Struct class smart enough to detect a question mark at the
> end of a member name and create the appropriate #member= and #member?
> methods?

It could have been made smart enough, but certain people decided that
sort of convenience was "incorrect programming".

See ruby-core:5796 and following.

Regards,

Dan