DDDD
DDDD

Reputation: 3940

If, elsif, else behavoir

I am learning Ruby and have simple If, Elsif, Else statements. The else is always run. I have read several examples and do not see what I did wrong.

if ip_voice.any?{ |o| @filter =~ /\b#{Regexp.escape(o)}\b/ }
      @catagory = "ip_voice"
elsif ip_pbx.any?{ |o| @filter =~ /\b#{Regexp.escape(o)}\b/ }
      @catagory = "ip_pbx"
elsif ip_video_surveillance.any?{ |o| @filter =~ /\b#{Regexp.escape(o)}\b/ }
      @catagory = "ip_video_surveillance"
elsif ip_video_telephony.any?{ |o| @filter =~ /\b#{Regexp.escape(o)}\b/ }
      @catagory = "ip_video_telephony"
elsif enterprise_gateways.any?{ |o| @filter =~ /\b#{Regexp.escape(o)}\b/ }
      @catagory = "enterprise_gateways"
else consumer_atas.any?{ |o| @filter =~ /\b#{Regexp.escape(o)}\b/ }
      @catagory = "consumer_atas"
        ...run code...
end

I have moved the statments in different orders and the code always runs well, just always the else statement. Am I missing something? Thank you

Upvotes: 0

Views: 150

Answers (1)

raina77ow
raina77ow

Reputation: 106375

There's exactly zero sense attaching any condition to else branch - this branch is executed only if checks for all the other branches (clauses given in if and elsif parts ) fail.

That's why Ruby treats your code as follows:

else 
  consumer_atas.any?{ |o| @filter =~ /\b#{Regexp.escape(o)}\b/ }
@catagory = "consumer_atas"

... i.e., always setting the @catagory variable with value specified in else.

Upvotes: 5

Related Questions