I have a couple more questions. Hopefully they’re not so dumb this time.
I need a hash that maintains insertion order. In Java, I’d use
LinkedHashMap. Does Ruby have one?
I like documentation. So far, Rdoc is great, but I wonder about the
following case:
class SomeClass
attr_accessor :someattr
But I need to validate, for example, so …
def someattr=(i) @someattr unless i < 10
end
end
In the above case, Ruby warns about the method being redefined (and the
original being discarded). However, if I change it to attr_reader to
avoid
that (i.e. manually make the reader) then RDoc lists the attribute as
read-only, with the writer shown as a normal method. This is perfectly
reasonable, but I feel there’s probably a way around it.
On Friday 09 December 2005 05:57 am, Ross B. wrote:
Hi,
I have a couple more questions. Hopefully they’re not so dumb this time.
I need a hash that maintains insertion order. In Java, I’d use
LinkedHashMap. Does Ruby have one?
I’ve only done Ruby for 9 days now, but from the reading I’ve done, no.
It
would be easy enough to insert the key in an array at the same time you
insert the key=>value in a hash. You could even make a class that does
it all
for you.
Perhaps there’s a better way, but that’s one I’m sure would work.
By the way, why do you need initial insertion order? Do you ever need to
look
up by the key value? If not, why not use an array of hashes, or an array
of 2
element arrays?
In the above case, Ruby warns about the method being redefined (and
the original being discarded). However, if I change it to
attr_reader to avoid that (i.e. manually make the reader) then RDoc
lists the attribute as read-only, with the writer shown as a normal
method. This is perfectly reasonable, but I feel there’s probably a
way around it.
end
Don’t use attr_accessor, then. attr_accessor doesn’t do any magic;
it’s
just a shorthand that defines default accessor methods.
This line:
attr_accessor :foo
has identical results to this code:
def foo
@foo
end
def foo=(new_foo)
@foo = new_foo
end
So if you’re going to define your own foo and foo=, just leave out the
attr_accessor line. If you’re only making your own foo=, you can use
attr_reader to get foo():
attr_reader :foo
def foo=
...
end
The other way around is less common, but still doable:
On Sat, 10 Dec 2005 00:36:34 +0900, James B. wrote:
James
Yup, that’s what I mean. I found I could do that, but I didn’t notice
it had documented them twice (just tried it and of course you’re right),
but I did see that Ruby warns me that the previous definition was
discarded. It’s not really a problem, but I do like to strive to be
warning-free