0

I have a rails controller and this code only loop through the first element in the metrics array? 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

1 Answer 1

2

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. Your method needs to look something like:

def values
  @metric = metrics.select do |metric|
    metric['href'].split('/').last == params[:id]
  end
end
Sign up to request clarification or add additional context in comments.

3 Comments

Oh i thought for every implicit return you could have an explicit return. Guess not.
@Catfish Every implicit return from a method or lambda, not blocks though.
@Catfish next is to blocks what return is to methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.