I have a a couple of quick questions. The first is this: I wish to
assign a value to a reference from within a block. However, the block
is out of scope and while I can initialise the reference beforehand, I
feel like I'm creating an object for no reason. So instead I do this:
def [](index)
if index.class == Symbol
@hash[index][:value]
elsif index.kind_of? Integer
value = nil # Assign value to nil
@hash.values.each { |h| value = h[:value] if h[:index] == index }
value
end
end
I assign value to nil because otherwise it does not exist out of the
block. But in Rubyland, that seems wrong somehow. Is there a better
(or nicer) way of doing this?
Second question is, does anyone know of an implementation of an
indexed or ordered hash? I know that's an oxymoron but I was curious
if anyone else has done it. I googled around but didn't find anything.
I needed a hash that could be ordered so I wrote something basic:
http://spannermonkey.bingodisk.com/bingo/public/spannermonkey/scripts/indexedhash.rb
But it would be nice if there was something done properly.
Sven
(I'm not even considering whether you should be perhaps a) inheriting
either Hash or Array instead of encapsulating one in your class, or b)
mixing Enumerable in, or c) some better idea).
ps: use rails-oceania@googlegroups. It's cooler =)
> I have a a couple of quick questions. The first is this: I wish to
> assign a value to a reference from within a block. However, the block
> is out of scope and while I can initialise the reference beforehand, I
> feel like I'm creating an object for no reason. So instead I do this:
>
> def [](index)
> if index.class == Symbol
> @hash[index][:value]
> elsif index.kind_of? Integer
> value = nil # Assign value to nil
> @hash.values.each { |h| value = h[:value] if h[:index] == index }
> value
> end
> end
>
> I assign value to nil because otherwise it does not exist out of the
> block. But in Rubyland, that seems wrong somehow. Is there a better
> (or nicer) way of doing this?
You could probably use inject:
@hash.values.inject(nil) {|acc, val| h[:index] == index ? h[:value] : acc }
Largely untested tho ;-)
> Second question is, does anyone know of an implementation of an
> indexed or ordered hash? I know that's an oxymoron but I was curious
> if anyone else has done it. I googled around but didn't find anything.
> I needed a hash that could be ordered so I wrote something basic:
Without reading your code, what kind of order are you talking about?
I usually go with a simple:
@hash.keys.sort.each{|key| ... }
.... but you're probably talking insertion order :-)
Take a look at: http://www.ruby-forum.com/topic/131494#586896
Cheers,
Assaph
Again, thanks.
The facets project includes an insertion order hash (the Dictionary class).
Cheers,
Gavin