> and I would like to get a value of the array knowing the :name by doing
a.find{|x| x[:name]=="pedro"}[:value]
#=> "lsss"
I tried this also, but stopped when I figured out that if there is no
match for the name, this will cause an exception... I did not
see an elegant solution for that case, with the data structure
that the OP proposes.
$ irb
001:0> a = [{:name => "pedro", :value => "Isss"}]
=> [{:name=>"pedro", :value=>"Isss"}]
002:0> a.find{|x| x[:name]=="pedro"}[:value]
=> "Isss"
003:0> a.find{|x| x[:name]=="mario"}[:value]
NoMethodError: undefined method `' for nil:NilClass
from (irb):3
from /home/peterv/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `<main>'
A general question I have is: are there hashes or arrays in Ruby
that offer a logarithmic look-up cost (e.g. implemented with a
btree, like an indexed column on a database). That would make
it really useful to make a better implementation (like you propose)
where you can look-up directly, based on the :name.
Thx,
Peter
···
On Tue, Oct 11, 2011 at 7:44 PM, botp <botpena@gmail.com> wrote:
On Wed, Oct 12, 2011 at 1:07 AM, Mario Ruiz <tcblues@gmail.com> wrote:
(Instead of just swallowing nils, it checks for the existence of a
method before calling it)
A general question I have is: are there hashes or arrays in Ruby
that offer a logarithmic look-up cost (e.g. implemented with a
btree, like an indexed column on a database).
Hashes are dynamically sized and will give you logarithmic lookup cost.
There are third-party libraries for trees; the main reason for using a
tree instead is so that you can insert nodes at particular places and
retrieve them from the same place.