试图找出在ruby中将两个数组中的值等同起来

时间:2016-01-30 19:00:55

标签: arrays ruby variables

当您输入与已存储在数组中的匹配单词的数字时,我正在尝试输出结尾。它目前只吐出两次数字。

puts "Welcome to the number-word machine app."

word = []

4.times do
  puts "Enter a word:"
  word << gets.chomp
end


x = [1, 2, 3, 4]
x = word

puts "enter a number:"
number = word
word = gets.chomp
puts word

2 个答案:

答案 0 :(得分:3)

您覆盖了word变量。您应该特别注意如何命名变量。

puts "Welcome to the number-word machine app."

words = []

4.times do
  puts "Enter a word:"
  words << gets.chomp
end

puts "Enter a number:"
number = gets.chomp

puts "You entered #{number}, which corresponds to:"
puts words[number.to_i]

答案 1 :(得分:1)

尝试为每个变量使用一个描述性名称。这使您更清楚自己想要做什么。

在您命名用户输入的号码word之前,这令人困惑。相反,请考虑将其命名为number

最后,要返回由输入数字的索引引用的数组中的单词,请执行puts words[number]

试试这个:

puts "Welcome to the number-word machine app."

words = []

4.times do
  puts "Enter a word:"
  words << gets.chomp
end

puts "Enter a number:"
number = gets.to_i
puts words[number]