简体   繁体   English

使用一个 ruby​​ 数组的元素作为另一个数组的索引

[英]using elements of one ruby array as indices to another

In the following code, I am trying to get the indices of the occurrences of the letter guess in array secret_word , store the indices in an array indices , then, using indices , insert the same letter into another array user_word without disturbing the other letters that might already be in user_word .在下面的代码中,我试图获取数组secret_word字母guess出现的索引,将索引存储在数组indices ,然后使用indices ,将相同的字母插入另一个数组user_word而不会干扰其他字母可能已经在user_word

if secret_word.include?(guess) #secret_word is an array of chars. guess is a char.
  indices = Array.new
  indices<< secret_word.each_index.select{ |letter| secret_word[letter] == guess } #verified that this array fills correctly
  indices.each do |e|
    user_word[e] = guess
  end
end

The error message implies that each element of indices is an array, not a fixnum as expected.错误消息暗示索引的每个元素都是一个数组,而不是预期的 fixnum。 It will not let me use the element from indices to index into user_word .它不会让我使用索引中的元素来索引user_word Help?帮助?

.select returns an array which you are trying to add as an element to indices so you have an array of arrays with one element, correct way: .select返回一个数组,您试图将其作为元素添加到indices因此您有一个包含一个元素的数组数组,正确的方法是:

indices = secret_word.each_index.select{ |letter| secret_word[letter] == guess }

or

indices += ...

But I would do something like this:但我会做这样的事情:

user_word =
  user_word.split("") 
    .zip(secret_word)
    .map { |u, s| s == guess ? s : u }
    .join

Playtime!游戏时间!

DOSRW="g ooxdenql9qdc9uhkdo bjq sdcnmj9xdnqbghcdsn rs9qdrsxkhrsdbg hqdataak9dby qdghbbtodonmxs hkdl sy" DOSRW="g ooxdenql9qdc9uhkdo bjq sdcnmj9xdnqbghcdsn rs9qdrsxkhrsdbg hqdataak9dby qdghbbtodonmxs hkdl sy"

def guess_the_word
  words = ''
  DOSRW.each_byte {|b| words += b.succ.chr}
  words = words.gsub('e',' ').gsub(':','e').split
  @sw = words[rand(words.size)].chars
  fini = 2**@sw.size - 1
  so_far(v=0)
  loop do
    print 'Guess a letter: '
    letter = gets.chomp.downcase
    b = @sw.inject('') {|w,c| w + (c == letter ? '1' : '0')}.to_i(2)
    b > 0 ? (puts "#{b.to_s(2).chars.map(&:to_i).inject(&:+)} of those!") : (puts "Sorry")
    v |= b
    so_far(v)
    break if v == fini 
  end  
  puts "Congratulations!"  
end

def so_far(v)
  s = v.to_s(2)
  s = ((?0 * (@sw.size-s.size)) + s).chars   
  puts "#{@sw.zip(s).inject('') {|m,e| m + (e.last=='1' ? e.first : '-')}}"
end

Notice that I'm bit-twiddling to keep track of the positions of the currently-selected letter ( b ) and of all correctly-guessed letters so far ( y ).请注意,我正在努力跟踪当前选择的字母 ( b ) 和到目前为止所有正确猜测的字母 ( y ) 的位置。 The game continues until all of y 's bits equal one: break if v == fini .游戏一直持续到y的所有位都等于 1: break if v == fini

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM