如何在ruby中使用for循环从哈希表中获取不同的值

时间:2010-11-26 11:00:09

标签: ruby

这可能很容易做到!我还没有想到循环,我正在考虑嵌套for循环但不太确定如何在两个哈希之间交替。

假设我有一个带有包含两个哈希表的def的类:

 class Teststuff
    def test_stuff
     letters = { "0" => " A ", "1" => " B ", "2" => " C " }
     position = {"1" => "one ", "2"=> " two ", "3"=> " three ", "4"=>" four " }

     my_array=[0,1,2,2] #this represents user input stored in an array valid to 4 elements
     array_size = my_array.size #this represents the size of the user inputed array
     element_indexer = my_array.size # parellel assignment so I can use same array for array in dex
     array_start_index = element_indexer-1 #give me the ability later to get start at index zero for my array

 #for loop?? downto upto?? 
 # trying to get loop to grab the first number "0" in element position "0", grab the hash values then
 # the loop repeats and grabs the second number "1" in element position "1" grab the hash values
 # the loop repeats and grabs the third number "2" in elements position "2" grab the hash values
 # the final iteration grabs the fourth number "2" in elements position "3" grab the hash values
 # all this gets returned when called. Out put from puts statement after grabing hash values 
 # is: **A one B two C three C four**  

     return a_string
    end
  end  

如何将字符串输出返回到屏幕,如下所示:

   **A one B two C three C four** 

或只是字母位置字母位置...... 感谢您的帮助,提出代码,以便我可以尝试我的编辑器!

3 个答案:

答案 0 :(得分:1)

您可以使用枚举器,如下所示:

l = letters.to_enum
p = position.to_enum
a_string = ''
loop do
  a_string << l.next[1] << p.next[1]
end

答案 1 :(得分:1)

我想我想出了你想要的是什么,虽然我仍然不知道array_sizeelement_indexerarray_start_indexTestStuff是什么。

def test_stuff
  letters = { "0" => " A ", "1" => " B ", "2" => " C " }
  position = {"1" => "one ", "2"=> " two ", "3"=> " three ", "4"=>" four " }

  my_array = [0, 1, 2, 2]

  "**#{my_array.map.with_index {|e, i|
    "#{letters[e.to_s].strip} #{position[(i+1).to_s].strip}"
  }.join(' ')}**"
end

[我冒昧地将您的代码重新格式化为标准的Ruby编码风格。]

然而,如果没有所有类型的转换,以及所有那些多余的空间,一切都会简单得多。此外,如果它实际上有一种方法可以返回不同的结果,而不是总是返回相同的东西,那么该方法会更有用,因为此刻,它实际上完全等同于

def test_stuff
  '**A one B two C three C four**'
end

这些方面的东西会更有意义:

def test_stuff(*args)
  letters = %w[A B C]
  position = %w[one two three four]

  "**#{args.map.with_index {|e, i| "#{letters[e]} #{position[i]}" }.join(' ')}**"
end

test_stuff(0, 1, 2, 2)
# => '**A one B two C three C four**'

如果您不想使用您的方法污染Object命名空间,可以执行以下操作:

def (TestStuff = Object.new).test_stuff(*args)
  letters = %w[A B C]
  position = %w[one two three four]

  "**#{args.map.with_index {|e, i| "#{letters[e]} #{position[i]}" }.join(' ')}**"
end

TestStuff.test_stuff(0, 1, 2, 2)
# => '**A one B two C three C four**'

答案 2 :(得分:0)

怎么样:

a_string = ""
my_array.each_with_index { |x, index|
  a_string += letters[my_array[index].to_s] + " " + (position.include?((index+1).to_s) ? position[(index+1).to_s] : "nil")
}