我在 Windows 10 x64 上运行 Ruby 2.3.1 x64。
我的代码:
class Credentials
attr_reader :username, :password
def initialize(username = nil, password = nil)
@username = username
@password = password
get_credentials if !@username || !@password #Gets credentials if none are specified
end
def get_credentials
@username = ask("Username: ") { |q| q.echo = true }
@password = ask("Password: ") { |q| q.echo = "*" }
end
end
忽略 get_credentials 的古怪之处,它是一个名为 Highline 的宝石,出于安全原因,我使用它来隐藏输入。
当我执行以下操作时:
$user = Credentials.new(username: "foo", password: "bar")
我得到这个回报:
#<Credentials:0x000000038ecf30 @password=nil, @username={:username=>"foo", :password=>"bar"}>
同样,调用 $user.username 会返回以下内容:
{:username=>"foo", :password=>"bar"}
什么时候应该返回:“foo”
并调用 $user.password 返回 nil。
有人能以亨利·汉密尔顿的名义告诉我为什么会这样吗?!我已经多次使用散列参数,它总是工作得很好。为什么要将每个参数设置填充到一个参数中?