附加的代码需要能够检查输入的数字是否在数组中,然后运行,如果为true,则运行,如果为false,则返回一条消息。
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
答案 0 :(得分:2)
这行是错误的
for v in (my_account)
应该是
for v in accounts
您要遍历accounts
数组中的数字,而不是my_account
,这只是一个数字
答案 1 :(得分:0)
您应该尝试:
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
答案 2 :(得分:0)
您应该使用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
将for
与puts
一起使用,将枚举数组中的所有项目。
例如:
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