What I would like to do is loop through the hash and do a different
action based on each unique key.
my_hash_table.each_pair do |k, v|
# Call a method if a hash key == "a"
# Call a different method if hash key == "b"
# Call a third method if a hash key == "c"
end
I have been trying to implement this with "if" and "case", but the loop
stops once the first argument is satisfied.
Can you please point into the right direction of how to go about solving
this problem.
What I would like to do is loop through the hash and do a different
action based on each unique key.
my_hash_table.each_pair do |k, v|
# Call a method if a hash key == "a"
# Call a different method if hash key == "b"
# Call a third method if a hash key == "c"
end
I have been trying to implement this with "if" and "case", but the loop
stops once the first argument is satisfied.
Then show your code. "if" and "case" will be able to do this just fine.
Make a small *standalone* test program, e.g. start it with
my_hash_table = {"a"=>42, "b"=>999, "c"=>123}
Then when you post it here, we will be able to run it too and duplicate
your problem.
Much more coherant. Abstracts detail of algorithm from loop body into
objects in well defined manner. Can be extended to do different things.
Cheers
Johnny
···
On Sat, 28 May 2011 04:44:20 +0900 Igor Nn <storm8000@gmail.com> wrote:
Hello -
I have a hash table of several items.
What I would like to do is loop through the hash and do a different
action based on each unique key.
my_hash_table.each_pair do |k, v|
# Call a method if a hash key == "a"
# Call a different method if hash key == "b"
# Call a third method if a hash key == "c"
end
def one(x)
puts "1. #{x}"
end
def two(x)
puts "2. #{x}"
end
def three(x)
puts "3. #{x}"
end
my_hash_table = {"a"=>42, "b"=>999, "c"=>123}
my_hash_table.each_pair do |k, v|
if k == "a"
one(v)
end
if k == "b"
two(v)
end
if k == "c"
three(v)
end
end
···
Igor Nn wrote in post #1001604:
What I would like to do is loop through the hash and do a different
action based on each unique key.
my_hash_table.each_pair do |k, v|
# Call a method if a hash key == "a"
# Call a different method if hash key == "b"
# Call a third method if a hash key == "c"
end
I have been trying to implement this with "if" and "case", but the loop
stops once the first argument is satisfied.
Then show your code. "if" and "case" will be able to do this just fine.
Make a small *standalone* test program, e.g. start it with
my_hash_table = {"a"=>42, "b"=>999, "c"=>123}
Then when you post it here, we will be able to run it too and duplicate
your problem.