简体   繁体   English

array.select不遍历每个元素

[英]array.select not iterating through every element

I have a rails controller and this code only loop through the first element in the metrics array? 我有一个rails控制器,并且此代码仅循环通过metrics数组中的第一个元素? Why is that? 这是为什么?

# /metrics/:id
def values
  @metric = metrics.select do |metric|
    id = metric['href'].split('/').last
    p "id == params[:id] = #{id == params[:id]}" # false on the first iteration (but never gets to the next iteration
    return id == params[:id]
  end
  p "HERE?" # We never get here!
end

You need to remove the return statement from your method, Ruby uses implicit return (see https://jtrudell.github.io/blog/ruby_return_values/ ), so the result of a block is the last line that is evaluated in that block, the return statement in your code is treated as a return from the values method. 您需要从方法中删除return语句,Ruby使用隐式return(请参阅https://jtrudell.github.io/blog/ruby_return_values/ ),因此, block的结果是该block中求值的最后一行,代码中的return语句被视为values方法的return Your method needs to look something like: 您的方法需要看起来像:

def values
  @metric = metrics.select do |metric|
    metric['href'].split('/').last == params[:id]
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM