Ruby - 从函数内部访问数组

时间:2015-03-14 21:12:06

标签: ruby arrays

Ruby Newb在这里。我尝试编写一个接受用户输入的程序,将其与数组中的数字进行比较,如果匹配,则将其添加到传递给该函数的另一个数字。像这样:

numbers = [1, 2, 3, 4, 5]

def add(start_num, list)
  print "What number will you add?> "
  number = gets.chomp

  if list.index(number) != nil
    start_num = start_num.to_i
    number = number.to_i
    sum = start_num + number
    puts "Your sum is #{sum}."
  else 
    puts "Not an acceptable number."
  end
end

add(10, numbers)

每当它达到list.index(number)nil的比较时,它显然都没有通过,并且吐出"不是可接受的答案。"因此,出于某种原因,即使用户输入的数字与numbers数组中的数字匹配,显然索引仍然等于nil

任何人都知道如何让测试通过?

3 个答案:

答案 0 :(得分:0)

只需将字符串转换为数字

即可
 number = gets.chomp.to_i

在您的代码中,您在列表中搜索<​​em>数字,这基本上是 string 。这就是您的if条件始终被评估为 falsy 的原因。顺便说一句,

number = gets.to_i 

也会工作。

答案 1 :(得分:0)

get.chomp是一个字符串我认为尝试使用gets.chomp.to_i将数字转换为数字

答案 2 :(得分:0)

从一个newb到另一个(我知道它可能很难,哈哈),这里有一些建议来清理你的代码(我确信有更清洁的版本,但这是一个开始)

numbers = [1, 2, 3, 4, 5]

def add(start_num, list)
  print "What number will you add?> "   #using puts will give the user a new line
  number = gets.chomp    #to_i is best placed here, gets.chomp ALWAYS returns a string

  if list.index(number) != nil   #include? is cleaner and more readable
    start_num = start_num.to_i   #an integer defined in an argument stays an integer, therefor no need for this line
    number = number.to_i     #no need for this line if you define it above
    sum = start_num + number
    puts "Your sum is #{sum}."
  else 
    puts "Not an acceptable number."
  end
end

add(10, numbers)

事实上,您可以使用terany缩短if语句...所以这是您的代码,更清晰的版本:

    numbers = [1, 2, 3, 4, 5]

def add(start_num, list)
  puts "What number will you add?"
  number = gets.chomp.to_i
  sum = start_num + number

  list.include?(number) ? puts("Your sum is #{sum}.") : puts("Not an acceptable number.")

end

add(10, numbers)

更少的代码更多;)

相关问题