“私有方法’被’征服’”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电话。