Tag Archives: switch/case

Always Identical Outputs? Switch Statement vs. Switch Expression

, ,

Are these two statements identical in what they return?

public object Switcher(bool flag) 
{
  switch (flag) {
    case true:
      return 1;
    case false:
     return 10.5;
  }
}
public object Switcher(bool flag) 
{
  return flag switch {
    true => 1,
    false => 10.5
  };
}

No.

TestResult –
Switch Statement
Result –
Switch Expression
Assert.Equal(1, x.Switcher(true));PassFail – Error Message:
Assert.Equal() Failure
Expected: 1 (System.Int32)
Actual: 1 (System.Double)
Assert.Equal(10.5, x.Switcher(false));PassPass

Scratching your head trying to find the difference? The logic in both looks identical. Arguably, it is.

Continue reading

Ruby: Case Testing Against Arrays of Values

,

Did you know that a when clause in a Ruby case statement can test against each item in an array? If any item in the array matches the case statement’s comparison (target) value, the when clause will evaluate to true.

In the below example, :express_truck will be returned if country matches any of the truckable_countries.

truckable_countries = ['United States', 'Canada', 'Mexico']

ship_via = case country
           when *truckable_countries
           	:express_truck
           else
           	:supersonic_jet
           end

Continue reading