From: Robert Klemme Date: 2012-02-01T21:33:42+09:00 Subject: Re: Multiple assignment in conditional On Wed, Feb 1, 2012 at 1:05 PM, Gavin Sinclair wrote: > On Wed, Feb 1, 2012 at 10:57 PM, Gavin Sinclair wrote: > > Sorry to reply to my own message, but I thought of something I should > have included. > > Here is the forbidden version I would like to write.  Obviously I'm > combining assignment and conditional, which may not win plaudits as a > general rule. > >>  def week_and_day(date) >>    if not self.include? date >>      return nil >>    elsif (week, day = @t1.week_and_day(date)) >>      return [week, day] >>    elsif (week, day = @t2.week_and_day(date)) >>      week += @t1.number_of_weeks >>      return [week, day] >>    end >>  end > > But consider this alternative, where I separate the assignment and the > conditional. > >  def week_and_day(date) >    if not self.include? date >      return nil >    else >      week, day = @t1.week_and_day(date) >      if week >        return [week, day] >      else >        week, day = @t2.week_and_day(date) >        week += @t1.number_of_weeks >        return [week, day] >      end >    end >  end > > I consider this very clumsy.  By _not_ combining assignment with > conditional, I cannot use "elsif".  I must split the "else" and the > "if", and turn the second conditional into a child instead of a > sibling. > > Definitely less intentional and unattractive code. There are plenty more solutions, for example: def week_and_day(date) return nil unless include? date week_and_day = @t1.week_and_day(date) and return week_and_day week_and_day = @t2.week_and_day(date) week_and_day[0] += @t1.number_of_weeks if week_and_day week_and_day end Maybe also def week_and_day(date) return nil unless include? date case when week_and_day = @t1.week_and_day(date) nil when week_and_day = @t2.week_and_day(date) week_and_day[0] += @t1.number_of_weeks end week_and_day end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/