本文介绍了为“parker"调用的“私有方法“gets":字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

我做错了什么?

推荐答案

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

There is a gets method in Kernel and Object includes Kernel. That means that almost everything includes Kernel so almost everything has a gets method. The intent of a lot of the (private) methods in Kernel is to allow you to treat some methods (such as gets) as plain functions so you can say things like:

s = gets

从标准输入读取.

当你这样做时:

"parker".gets.chomp.capitalize!

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

You're calling the private gets from Kernel on a String but calling private methods with an explicit receiver is a NoMethodError.

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

If you want to read the first name from the standard input then you just want this:

first_name = gets.chomp.capitalize

对于其他 gets 调用也类似.

Similarly for the other gets calls.

这篇关于为“parker"调用的“私有方法“gets":字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 17:09