Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

Ruby stop iterate in case block if return true

I've got below if block:

  scoring = if match_invoice_number(resource)
              3
            elsif match_amount(resource) && match_vendor(resource)
              2
            elsif match_vendor(resource)
              1
            else
              0
            end

which I replace by below case:

  def score(resource)
    case resource
    when match_invoice_number(resource) then 0
    when match_amount(resource) && match_vendor(resource) then 1
    when match_vendor(resource) then 3
    else -1
    end
  end

I thought it would break this loop when some when element returned true. E.g. match_amount(resource) && match_vendor(resource) will return true - it case break and return 1. How to achieve that?

question from:https://stackoverflow.com/questions/65936736/ruby-stop-iterate-in-case-block-if-return-true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In case resource ruby compares your resource with every expression using ===. It seems, that match... methods returns booleans, so that you will always get a default value.

To make this work you could get rid of resource. With empty case you will get an expected behaviour.

def score(resource)
  case
  when match_invoice_number(resource) then 0
  when match_amount(resource) && match_vendor(resource) then 1
  when match_vendor(resource) then 3
  else -1
  end
end

However, it is not a good practice to use empty cases. If-else is the tool that solves this task better.

def score(resource)
  if match_invoice_number(resource)
    3
  elsif match_amount(resource) && match_vendor(resource)
    2
  elsif match_vendor(resource)
    1
  else
    0
  end
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...