Struct.new and symbol with question mark

S

Suraj Kurapati

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
=> nil
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.
 
M

Morton Goldberg

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

=> nil

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
 
D

Daniel Berger

Suraj said:
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
 

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,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top