【问题标题】:"private method 'gets' called for "parker":String“为“parker”调用私有方法“gets”:字符串
【发布时间】:2013-10-31 05:11:12
【问题描述】:

这是我的代码:

print "What's your first name"
first_name = "p".gets.chomp.capitalize!
puts "#{first_name}"
puts "Your name is #{first_name}!"
print "What's your last name?"
last_name = "m".gets.chomp.capitalize!
puts "#{last_name}"
puts "Your name is #{last_name}!"
print "What city do you live in?"
city = "world".gets.chomp.capitalize!
puts "#{city}"
puts "You live in #{city}!"
print "What state do you live in?"
state = "OR".gets.chomp.upcase!
puts "#{state}"
puts "You live in the state of #{state}!"

但我不断收到此错误:

private method `gets' called for "p":String

我做错了什么?

【问题讨论】:

  • 你正在尝试输入表单用户..对吗?

标签: ruby ruby-on-rails-3


【解决方案1】:

有一个gets method in KernelObject 包括Kernel。这意味着几乎所有东西都包含Kernel,所以几乎所有东西都有gets 方法。 Kernel 中的许多(私有)方法的目的是允许您将某些方法(例如 gets)视为普通函数,以便您可以这样说:

s = gets

从标准输入读取。

当你这样做时:

"parker".gets.chomp.capitalize!

您在 String 上从 Kernel 调用私有 gets,但使用显式接收器调用私有方法是 NoMethodError

如果您想从标准输入中读取名字,那么您只需要这样:

first_name = gets.chomp.capitalize

对于其他 gets 调用也是如此。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 2014-03-29
    • 2013-02-26
    • 1970-01-01
    • 2018-05-03
    相关资源
    最近更新 更多