简体   繁体   English

Ruby中用于“puts {} .class”的意外行为

[英]Unexpected behaviour in Ruby for “puts {}.class”

puts {}.class

#=> NilClass 

puts "".class
String
#=> nil 

puts [].class
Array
#=> nil

Why is puts {}.class not showing Hash as output and then nil like the others? 为什么puts {}.class不显示Hash作为输出,然后像其他人一样nil

puts {} is interpreted as puts method call with empty block passed into it, hence the empty result. puts {}被解释为puts方法调用,其中传入空块,因此为空结果。 puts({}.class) works as you expect. puts({}.class)按预期工作。

There are a couple things to understand: 有几点需要了解:

  1. whenever a hash is the first argument to a method being called, you need to use parenthesis or remove the braces, otherwise ruby thinks it's a block. 每当哈希是被调用方法的第一个参数时,你需要使用括号或删除大括号,否则ruby认为它是一个块。 So puts { foo: "bar" } raises a syntax error, but puts foo: "bar" , puts(foo: "bar") , or puts({foo: "bar"}) work fine. 所以puts { foo: "bar" }会引发语法错误,但puts foo: "bar"puts(foo: "bar")puts({foo: "bar"})工作正常。

  2. every method can be called with a block, however only some methods actually call the block. 可以使用块调用每个方法,但只有一些方法实际上调用了块。 You can test it for yourself - puts(1) { raise } just outputs the number, and doesn't raise an error. 您可以自己测试 - puts(1) { raise }只输出数字,并且不会引发错误。 puts { 1 } prints nothing, because the block isn't called. puts { 1 }什么都不打印,因为没有调用块。

  3. The puts method always returns nil. puts方法总是返回nil。 So when you say puts {}.class , that's basically the same as puts.class , which is NilClass 因此,当你说puts {}.class ,它与puts.class基本相同,它是NilClass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM