Ste*_*sky 2 ruby conditional-statements
在Perl中,我经常发现自己使用以下模式:
croak "incompatible object given: $object"
unless $object->isa('ExampleObject') and $object->can('foo');
Run Code Online (Sandbox Code Playgroud)
我试图像这样将其翻译成Ruby:
raise ArgumentError, "incompatible object given: #{object.inspect}"
unless object.is_a?(ExampleObject) and object.respond_to?(:foo)
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为Ruby解释unless为新语句的开始。据我了解,我可以在第一行的末尾加一个反斜杠,但这看起来很丑,而且感觉不对。我也可以使用常规unless condition raise error end结构,但是我更喜欢原始表单的样式。有没有一种很好的(惯用的)方式将其作为单个语句写在Ruby中?
我可以在Ruby的下一行放置if / unless子句吗?
你不能 通常不相关的ISO Ruby最终草案的第107页(PDF页面127),但是像这样的基本内容也使我们不必阅读parse.y:
unless-modifier-statement ::
statement [no line-terminator here] unless expression
Run Code Online (Sandbox Code Playgroud)
这很清楚。它只是与您的Perl示例相似,没有:
raise ArgumentError, "incompatible object given: #{object.inspect}" unless
object.is_a?(ExampleObject) and object.respond_to?(:foo)`
Run Code Online (Sandbox Code Playgroud)
要么:
raise ArgumentError, "incompatible object given: #{object.inspect}" \
unless object.is_a?(ExampleObject) and object.respond_to?(:foo)
Run Code Online (Sandbox Code Playgroud)