簡體   English   中英

使用一個 ruby​​ 數組的元素作為另一個數組的索引

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

在下面的代碼中,我試圖獲取數組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

錯誤消息暗示索引的每個元素都是一個數組,而不是預期的 fixnum。 它不會讓我使用索引中的元素來索引user_word 幫助?

.select返回一個數組,您試圖將其作為元素添加到indices因此您有一個包含一個元素的數組數組,正確的方法是:

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

indices += ...

但我會做這樣的事情:

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

游戲時間!

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

請注意,我正在努力跟蹤當前選擇的字母 ( b ) 和到目前為止所有正確猜測的字母 ( y ) 的位置。 游戲一直持續到y的所有位都等於 1: break if v == fini

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM