【问题标题】:Ruby True/False Array [closed]Ruby True/False 数组 [关闭]
【发布时间】:2019-03-19 22:24:42
【问题描述】:

附加代码需要能够检查输入的数字是否在数组中,如果为真则运行,如果为假则返回消息。

accounts = [5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 8080152, 4562555, 5552012, 5050552, 7825877, 1250255,
       1005231, 6545231, 3852085, 7576651, 7881200, 4581002,]
puts "What is your account number?"
my_account = gets.to_i
for v in (my_account)
  if v ==(my_account) 
    puts "Welcome to your account"
  end
end

【问题讨论】:

  • 5658845 的未定义方法“每个”:不断发生的整数错误
  • 您需要确认gets.chomp 是自然数(非负整数)的字符串表示形式。例如,如果gets => "cat\n"my_account = gets.to_i #=> 0 并且您将愉快地检查accounts 是否包含零。请参阅String#to_i 以了解为什么"cats\n".to_i #=> 0。您可以使用正则表达式进行检查。如果它应该是一个自然数,gets.chomp =~ /\D/true 如果gets.chomp 包含一个数字以外的字符,那么你需要!(gets.chomp =~ /\D/)gets.chomp !~ /\D/)

标签: arrays ruby


【解决方案1】:

这一行是错误的

for v in (my_account)

应该是

for v in accounts

你想遍历accounts数组中的数字,而不是my_account,那只是一个数字

【讨论】:

    【解决方案2】:

    你应该试试:

    accounts = [5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 8080152, 4562555, 5552012, 5050552, 7825877, 1250255,
           1005231, 6545231, 3852085, 7576651, 7881200, 4581002,]
    puts "What is your account number?"
    my_account = gets.to_i
    if accounts.include?(my_account)
      puts "Welcome to your account"
    else
      # do whatever you need to do
    end
    

    【讨论】:

    • 为什么数组的最后一个元素后面要加逗号?
    【解决方案3】:

    你应该使用Array#include?

    accounts = [5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 8080152, 4562555, 5552012, 5050552, 7825877, 1250255, 1005231, 6545231, 3852085, 7576651, 7881200, 581002]
    puts 'What is your account number?'
    my_account = gets.to_i
    
    if accounts.include?  my_account
      puts 'Welcome to your account'
    else
      puts 'It is not you account'
    end
    

    forputs 一起使用,您将枚举数组中的所有项目。

    例如:

    accounts = [1, 2, 3]
    puts "What is your account number?"
    my_account = gets.to_i
    
    for v in accounts
      if v == my_account
        puts "Welcome to your account #{v}"
      else
        puts "#{v} is not your account"
      end
    end
    
    # What is your account number?
    # 2
    # 1 is not your account
    # Welcome to your account 2
    # 3 is not your account
    

    【讨论】:

    • 好吧,在最坏的情况下,Array#include? 也会遍历整个数组 :)
    猜你喜欢
    • 2012-02-27
    • 2013-06-22
    • 2016-04-08
    • 2013-01-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多