Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ruby中是否有each_if?_Ruby_Conditional_Each - Fatal编程技术网

ruby中是否有each_if?

ruby中是否有each_if?,ruby,conditional,each,Ruby,Conditional,Each,假设我在Ruby中有每个循环 @list.each { |i| puts i if i > 10 break end } 我想在列表中循环,直到满足条件 这让我感到“不懂Ruby”,既然我是Ruby新手,有没有Ruby方法可以做到这一点?你可以使用,或者,根据你想要的结果 @list.detect { |i| puts i i > 10 } # Returns the first element greater than 10, or nil. 正如

假设我在Ruby中有每个循环

@list.each { |i|
  puts i

  if i > 10
    break
  end
}
我想在列表中循环,直到满足条件

这让我感到“不懂Ruby”,既然我是Ruby新手,有没有Ruby方法可以做到这一点?

你可以使用,或者,根据你想要的结果

@list.detect { |i|
  puts i
  i > 10
} # Returns the first element greater than 10, or nil.
正如其他人所指出的,一种更好的方式是首先进行子选择,然后根据选择采取行动,例如:

@list.take_while{ |i| i <= 10 }.each{|i| puts i}

@list.take_while{i | i您可以使用take_while:

@list.take_while { |i| i <= 11 }.each { |i| puts i }

@list.take_while{i |我可能太正统了,但我会觉得使用“take_while”或“detect”有点不舒服,这意味着功能性的使用(它们返回一些东西),会产生一些副作用。也就是说,它们会按照OP的要求进行操作。所以可能:@list.take_while{…}.each.好的,这是mattexx的答案。很抱歉,太迂腐了,但是你通常会用四个空格缩进你的Ruby代码吗?没关系:注意到OP也是这样做的。但是这样你会重复两次。有没有办法将一个条件传递给一个
each
,然后只在匹配该条件的元素上执行该块?