我有将用户输入数据读入数组的方法,我有另一种方法,通过一些处理将相同数组中的值显示给用户。
然而,这似乎不是正确的方法,因为系统总是抛出一个
Arraypass.rb:23:在<main>': undefined local variable or method
名称中为main:Object(NameError)
感谢有人能在此展示出前进的方向,
例如:
class School
def askdetails
print "How many students are there"
n=(gets.chomp.to_i - 1)
print "Enter names one by one"
names=Array.new(n)
for i in (0..n)
names[i]=gets.chomp
end
return names,n
end
def showdetails(names,n)
for i in (0..n)
puts names[i]
end
end
end
stud=School.new
stud.askdetails
stud.showdetails(names,n)
答案 0 :(得分:1)
将代码编写为
#!/usr/bin/env ruby
class School
def askdetails
print "How many students are there"
n = gets.chomp.to_i - 1
print "Enter names one by one"
names = Array.new(n)
for i in (0..n)
names[i]=gets.chomp
end
return names,n
end
def showdetails(names,n)
for i in (0..n)
puts names[i]
end
end
end
stud = School.new
names, n = stud.askdetails
stud.showdetails(names,n)
你遗漏的是#askdetails
方法返回Array
的方法,你在使用之前没有指定任何地方。
阅读Array Decomposition,这就是我在这里所做的:
names, n = stud.askdetails
答案 1 :(得分:0)
这是你的答案:
names,n = stud.askdetails
stud.showdetails(names,n)