From: Robert Klemme Date: 2011-01-12T22:21:37+09:00 Subject: Re: Case statements - Just beautification On Wed, Jan 12, 2011 at 12:50 PM, flebber wrote: > On Jan 12, 10:43 pm, flebber wrote: >> I just want to clarify case statements the name after the word case is >> this just for beautification and to help with code readability? What >> purpose does it serve. >> >> So in my code its "winunit" and matz's code its "birthyear". >> >> # Method 1 - Confident - assign range >> # number -> number >> def pricerange(x) >> puts "Enter the quoted price: " >> x = gets.chomp >> winalloc = case winunit >>   when x == (1.50...2.50) then ... >>   when x == (2.50...3.80) then ... >>   when x == (3.80...5.50) then ... >>   else something >> end >> >> # Case expression tests ranges with === >> generation = case birthyear >>              when 1946..1963: "Baby Boomer" >>              when 1964..1976: "Generation X" >>              when 1978..2000: "Generation Y" >>              else nil >>              end >> >> Sayth > > Oops edited mine to look more like Matz's > > def pricerange(x) > puts "Enter the quoted price: " > x = gets.chomp > winalloc = case winunit >          when x == 1.50...2.50: ... >          when x == 2.50...3.80: ... >          when x == 3.80...5.50: ... >          else something > end This won't work they way you probably expect. It will evaluate "x == ..." expressions to a boolean value (true or false) and then evaluate true|false === winunit which will only ever be true if winunit itself is true or false. You need to decide which of the two forms of case you want to use 1. with a single value case x when A when B when C else end In this case A|B|C === x is evaluated and if it returns a trueish value the corresponding branch will be evaluated. 2. without value case when D > x when E.include? x when its_too_late() else end In this case each expression after "when" is evaluated and if it returns a trueish value the corresponding branch will be evaluated. Note: trueish values are all values except nil and false. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/