草庐IT

Ruby one liner for method undefined or nil

我很好奇是否有更短的方法来检查对象上是否定义了方法,如果是,则检查它是否为nil。我试过:if!obj.respond_to?(:meth)||obj.meth.nil?但是看起来又长又丑。 最佳答案 快速而肮脏但简洁:unless(obj.methrescuenil)...end如果将meth发送到obj失败(例如,因为缺少方法),表达式将取值nil。当然这隐藏了meth中的各种错误。 关于Rubyonelinerformethodundefinedornil,我们在StackOver

ruby - 使用 ruby​​ 代码中的 ruby​​ one liners

我读到了DaveThomasRubyoneliners它说#printsectionoffilebetweentworegularexpressions,/foo/and/bar/$ruby-ne'@found=trueif$_=~/foo/;nextunless@found;puts$_;exitif$_=~/bar/'我可以知道如何使用我的Ruby代码而不是命令行吗? 最佳答案 根据ruby​​CLI引用,-nassume'whilegets();...end'looparoundyourscript-e'command'one