Why is def foo? legal but @foo? illegal?

G

Gavin Kistner

Can someone tell me why you can define a method with a question mark in
its name...

def initialize
@foo=true
end
def foo?
@foo
end


....but you can't name an instance variable with one:

attr_reader:)foo?)
def initialize
@foo?=true
end
 
C

Chris Morris

Gavin said:
....but you can't name an instance variable with one:

attr_reader:)foo?)
def initialize
@foo?=true
end


Don't know if it is possible, but I know the above won't work because
you used attr_reader which will create a getter, but no setter for foo?.
Try changing it to attr_accessor and see if that works.
 
Z

Zachary P. Landau

--pf9I7BMVVzbSWLtt
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable
=20
Don't know if it is possible, but I know the above won't work because=20
you used attr_reader which will create a getter, but no setter for foo?.= =20
Try changing it to attr_accessor and see if that works.

But he wasn't using the accessor in initialize, he was changing the
variable directly. foo? =3D true would be using the accessor.

--
Zachary P. Landau <[email protected]>
GPG: gpg --recv-key 0x24E5AD99 | http://kapheine.hypa.net/kapheine.asc

--pf9I7BMVVzbSWLtt
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFAGWZQCwWyMCTlrZkRAiKqAJ9bZvpBWSjyzopL3CXKAQ9xP5Bq2ACeJeky
5RjrlLWjheEQi6Upsdw9MEI=
=Sv7b
-----END PGP SIGNATURE-----

--pf9I7BMVVzbSWLtt--
 
G

Gavin Kistner

Chris said:
attr_reader:)foo?)
def initialize
@foo?=true
end

[...] but I know the above won't work because
you used attr_reader which will create a getter, but no setter for foo?.

What? You don't need a public setter function to set the value of an
instance variable. That's the whole point of attr_reader :)

For example, the following code works just fine:

class Bar
attr_reader:)foo)
def initialize
@foo=true
end
end

bar = Bar.new
puts bar.foo


as does this code:

class Bar
def initialize
@foo=true
end
def foo?
return @foo
end
end

bar = Bar.new
puts bar.foo?

My only point is that if I could name an instance variable @foo? then
the code quoted at the top of this post would work, and be slightly less
verbose.

I suppose it's not allowed because you can define a method named foo?
but not one named foo?= (thus enforcing the idea that a method ending in
a question mark is for querying a boolean aspect of an instance, and not
for setting one) and you might want to be able to publicly set the state
of a @foo? variable.
 

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,141
Messages
2,570,818
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top