hash

J

jason joo

[Note: parts of this message were removed to make it a legal post.]

the keys for a hash are uniq.
what do u mean by 'repeat'?
 
D

Dmitriy Makarov

what do u mean by 'repeat'?

axample in java
HashMap h=ne HashMap();
h.put("key","value_1");
h.put("key","value_2");
h.put("key","value_N");

how to made in ruby
 
P

Peter Hickman

The Ruby hash is not a Java HashMap

x["key"] = "value_1"
x["key"] = "value_2"

puts x["key"] => "value_2"

The best you can do is:
1) Create a HashMap class for Ruby, a very simple task
2) Use lists to store the values

x["key"] = Array.new
x["key"] << "value_1"
x["key"] << "value_2"

puts x["key"] => ["value_1", "value_2"]
 
J

jason joo

[Note: parts of this message were removed to make it a legal post.]

another way is to make a patch to Hash object, put ur own rules in it and u
will have a HashMap in ruby

2010/8/10 Peter Hickman said:
The Ruby hash is not a Java HashMap

x["key"] = "value_1"
x["key"] = "value_2"

puts x["key"] => "value_2"

The best you can do is:
1) Create a HashMap class for Ruby, a very simple task
2) Use lists to store the values

x["key"] = Array.new
x["key"] << "value_1"
x["key"] << "value_2"

puts x["key"] => ["value_1", "value_2"]
 
J

jason joo

[Note: parts of this message were removed to make it a legal post.]

actually u just need a method to put value in and return the overwrite
value, don't u?
so in a usual way u can write a Hash class to redefine its []= method to
acheive that

2010/8/10 Jake Jarvis said:
The Ruby hash is not a Java HashMap

x["key"] = "value_1"
x["key"] = "value_2"

puts x["key"] => "value_2"

The best you can do is:
1) Create a HashMap class for Ruby, a very simple task
2) Use lists to store the values

x["key"] = Array.new
x["key"] << "value_1"
x["key"] << "value_2"

puts x["key"] => ["value_1", "value_2"]

Why do that?
That's not how the given Java code behaves.
 
B

Brian Candler

Dmitriy said:

(1)

myhash = Hash.new { |h,k| h[k] = [] }
myhash['key'] << 'val1'
myhash['key'] << 'val2'
myhash['key'] << 'val3'
p myhash
# {"key"=>["val1", "val2", "val3"]}
p myhash['key']
# ["val1", "val2", "val3"]

(2)

myhash = Hash.new { |h,k| h[k] = {} }
myhash['key']['val1'] = true
myhash['key']['val2'] = true
myhash['key']['val3'] = true
p myhash
# {"key"=>{"val3"=>true, "val1"=>true, "val2"=>true}}
p myhash['key'].keys
# ["val3", "val1", "val2"]

The latter has the property that duplicate values are eliminated, and
it's very quick to test for a particular value:

if myhash['key']['val1']
... etc
end
 

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
474,146
Messages
2,570,832
Members
47,374
Latest member
EmeliaBryc

Latest Threads

Top