On Wed, Feb 1, 2012 at 1:05 PM, Gavin Sinclair <gsinclair / gmail.com> wrote:
> On Wed, Feb 1, 2012 at 10:57 PM, Gavin Sinclair <gsinclair / gmail.com> wro=
te:
>
> 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. =A0Obviously I'm
> combining assignment and conditional, which may not win plaudits as a
> general rule.
>
>> =A0def week_and_day(date)
>> =A0 =A0if not self.include? date
>> =A0 =A0 =A0return nil
>> =A0 =A0elsif (week, day =3D @t1.week_and_day(date))
>> =A0 =A0 =A0return [week, day]
>> =A0 =A0elsif (week, day =3D @t2.week_and_day(date))
>> =A0 =A0 =A0week +=3D @t1.number_of_weeks
>> =A0 =A0 =A0return [week, day]
>> =A0 =A0end
>> =A0end
>
> But consider this alternative, where I separate the assignment and the
> conditional.
>
> =A0def week_and_day(date)
> =A0 =A0if not self.include? date
> =A0 =A0 =A0return nil
> =A0 =A0else
> =A0 =A0 =A0week, day =3D @t1.week_and_day(date)
> =A0 =A0 =A0if week
> =A0 =A0 =A0 =A0return [week, day]
> =A0 =A0 =A0else
> =A0 =A0 =A0 =A0week, day =3D @t2.week_and_day(date)
> =A0 =A0 =A0 =A0week +=3D @t1.number_of_weeks
> =A0 =A0 =A0 =A0return [week, day]
> =A0 =A0 =A0end
> =A0 =A0end
> =A0end
>
> I consider this very clumsy. =A0By _not_ combining assignment with
> conditional, I cannot use "elsif". =A0I 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 =3D @t1.week_and_day(date) and return week_and_day

   week_and_day =3D @t2.week_and_day(date)
   week_and_day[0] +=3D @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 =3D @t1.week_and_day(date)
     nil
   when week_and_day =3D @t2.week_and_day(date)
     week_and_day[0] +=3D @t1.number_of_weeks
   end

   week_and_day
 end

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/