From: Bob Nadler Date: 2010-07-13T05:17:25+09:00 Subject: Re: what about allowing to specify, which end belongs to which start? On Mon, Jul 12, 2010 at 3:30 PM, Jan Lelis wrote: >> > def test >> >  while 1 >> >    puts (1..9).each_slice(3).map do |slice| >> >      sum = slice.inject do |acc, ele| >> >        acc + ele >> >      end >> > >> >      if sum > 6 >> >        42 >> >      else >> >        99 >> >      end~if >> >    end~do.join ',' >> >  end~while >> > end >> > >> Hi, >> I know it's a bit of a contrived example, and I'm not advocating a version >> of "Ruby Golf" here, but if I saw this method in some code I was maintaining >> I would refactor it to something like: >> >> def test >>   while 1 >>     puts (1..9).each_slice(3).map do |slice| >>       sum = slice.inject { |acc, ele| acc + ele } >>       sum > 6 ? 42 : 99 >>     end.join(',') >>   end >> end >> >> ...or even better, move the "summing" to another method... >> >> def test >>   while 1 >>     puts (1..9).each_slice(3).map do |slice| >>       calculate_sum > 6 ? 42 : 99 >>     end.join(',') >>   end >> end >> >> def calculate_sum(items) >>   items.inject { |acc, ele| acc + ele } >> end >> >> I think most cases where the end~if syntax is "necessary" would be better off >> (e.g. more readable) with a healthy dose of refactoring. >> > > Of course, the example was made up to demonstrate the ends and not real > world code. I would not write it in this way, either... > > This one is from existing code: > >  module ABC > >    # ... > >    def abc >      x.each do >        if x > >          case lorem > >          when :ipsum >            # ... >          when :ipsum >            # ... >          when :ipsum >            # ... >          when :ipsum >            # ... >          else >            # ... >          end >        end >      end >    end >  end > My general rule of thumb is to put long case statements (if I can't avoid using them) into their own separate method. So I would refactor the code to: module ABC def abc x.each do some_method_name_that_describes_what_case_statement_does(lorem) if x end end def some_method_name_that_describes_what_case_statement_does(value) case lorem when :ipsum # ... when :ipsum # ... when :ipsum # ... when :ipsum # ... else # ... end end end As an aside, take a look at Refactoring: Ruby Edition[1]. It covers ways of dealing with long methods, case statements, and other situations that cause difficulties trying to match up "end"'s. [1] http://www.amazon.com/Refactoring-Ruby-Jay-Fields/dp/0321603508