ruby-on-rails – 如何使用注入ruby的下一个

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何使用注入ruby的下一个前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我写的代码如下:
  1. [1,2,3,4,5].inject([]) do |res,a|
  2. res << a*a and next if a == 2
  3. res << a
  4. end

它给出以下错误

  1. NoMethodError: undefined method `<<' for nil:NilClass

由于接下来它使res变量为nil,如何解决这个问题?

我尝试了各种各样的方法,但是接下来无法使用ruby,我知道我提供的这个片段可以在没有下一个的情况下完成(a == 4?res<< a * a:res<< a),但在我的实际用例中,我有一些复杂的逻辑,不能简单地完成.

解决方法

更换
  1. res << a*a and next if a == 2

  1. next res << a*a if a == 2

现在,它会工作.

示例: –

  1. #!/usr/bin/env ruby
  2.  
  3. ar = [1,a|
  4. next res << a*a if a == 2
  5. res << a
  6. end
  7.  
  8. p ar
  9. # >> [1,5]

Read the documentation of next

next can take a value,which will be the value returned for the current iteration of the block….

猜你在找的Ruby相关文章