[英]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.