“私有方法’被’征服’”parker“:字符串
这是我的代码:
print "What's your first name" first_name = "parker".gets.chomp.capitalize! puts "#{first_name}" puts "Your name is #{first_name}!" print "What's your last name?" last_name = "mitchell".gets.chomp.capitalize! puts "#{last_name}" puts "Your name is #{last_name}!" print "What city do you live in?" city = "Carlsbad".gets.chomp.capitalize! puts "#{city}" puts "You live in #{city}!" print "What state do you live in?" state = "CA".gets.chomp.upcase! puts "#{state}" puts "You live in the state of #{state}!"
我不断收到此错误:
private method `gets' called for "parker":String
我究竟做错了什么?
Kernel
有一个gets
方法,而Object
包含Kernel
。 这意味着几乎所有东西都包含Kernel
所以几乎所有东西都有一个gets
方法 Kernel
许多(私有)方法的目的是允许您将某些方法(例如gets
)视为普通函数,因此您可以这样说:
s = gets
从标准输入读取。
当你这样做:
"parker".gets.chomp.capitalize!
你在String
调用私有来自Kernel
但是使用显式接收器调用私有方法是NoMethodError
。
如果您想从标准输入中读取名字,那么您只需要:
first_name = gets.chomp.capitalize
同样地,对于其他gets
电话。