ruby-on-rails – 如何使用注入ruby的下一个
发布时间:2020-12-16 19:15:17 所属栏目:百科 来源:网络整理
导读:我写的代码如下: [1,2,3,4,5].inject([]) do |res,a| res a*a and next if a == 2 res aend 它给出以下错误: NoMethodError: undefined method `' for nil:NilClass 由于接下来它使res变量为nil,如何解决这个问题? 我尝试了各种各样的方法,但是接下来无法
我写的代码如下:
[1,2,3,4,5].inject([]) do |res,a| res << a*a and next if a == 2 res << a end 它给出以下错误: NoMethodError: undefined method `<<' for nil:NilClass 由于接下来它使res变量为nil,如何解决这个问题? 我尝试了各种各样的方法,但是接下来无法使用ruby,我知道我提供的这个片段可以在没有下一个的情况下完成(a == 4?res<< a * a:res<< a),但在我的实际用例中,我有一些复杂的逻辑,不能简单地完成. 解决方法
更换
res << a*a and next if a == 2 同 next res << a*a if a == 2 现在,它会工作. 示例: – #!/usr/bin/env ruby ar = [1,a| next res << a*a if a == 2 res << a end p ar # >> [1,5] Read the documentation of
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读