Как использовать цикл for в ruby, чтобы получить разные значения из хеш-таблиц - PullRequest
0 голосов
/ 26 ноября 2010

Это, вероятно, легко сделать!Я пока не могу представить цикл, я думал о вложенном цикле 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 ]

1 голос
/ 26 ноября 2010

Мне кажется, я понял, чего вы хотите, хотя я до сих пор не знаю, для чего array_size, element_indexer, array_start_index и 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]

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

[Iвзял на себя смелость переформатировать ваш код в стандартный стиль кодирования Ruby.]

Однако все было бы намного проще, если бы не было всех этих преобразований типов и всех этих лишних пробелов.Кроме того, этот метод был бы гораздо более полезным, если бы он действительно мог возвращать разные результаты, вместо того, чтобы всегда возвращать одно и то же, потому что в настоящий момент он фактически точно эквивалентен

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

Somethingв этом смысле имело бы гораздо больше смысла:

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**'
1 голос
/ 26 ноября 2010

Вы можете использовать перечислители, например так:

l = letters.to_enum
p = position.to_enum
a_string = ''
loop do
  a_string << l.next[1] << p.next[1]
end
0 голосов
/ 26 ноября 2010

Как насчет:

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")
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...