F. Senault
1/14/2009 10:39:00 PM
Le 14 janvier 2009 à 16:56, Taylor Strait a écrit :
> This does not because of the return statements. However, I need to
> reverse the result for those two options. How can I do this with case
> statements? Or must I use if..elsif?
To go a step further than just answering your question, I'd refactor the
whole function like this :
def single_choice(object)
l = case object.list_method
when /^position/ then lambda { |x| x.position }
when /^rand/ then lambda { rand }
when /^alpha/ then lambda { |x| x.to_s }
when /^length/ then lambda { |x| x.length }
end
sorted_answers = object.answers.sort_by(&l)
if order =~ /desc$/
sorted_answers.reverse!
end
sorted_answers
end
The lamba is there to avoid the repetition of the sort_by calls, the use
of regexpen means you have to standardize your methods (length and
length_desc vs shortest_firts and longest_first). On the other hand,
you can manage all kind of sorts without duplicating your sort method.
An even nicer form, if your arrays are of a manageable size, would be :
def single_choice(object)
r = (object.list_method =~ /desc/ ? -1 : 1)
l = case object.list_method
when /^position/ then lambda { |x, y| (x.position <=> y.position) * r }
when /^rand/ then lambda { rand }
when /^alpha/ then lambda { |x, y| (x.to_s <=> y.to_s) * r }
when /^length/ then lambda { |x, y| (x.length <=> y.length) * r }
end
object.answers.sort(&l)
end
(But sort is slower for big arrays.)
You can also extract the case expression into a helper method if you
need to sort other kinds of objects...
HTH,
Fred
--
"- Anyway, United Amalgamated Consolidated Holdings probablt don't worry
about that sort of thing. They've probabbly got a Vice-President in
Charge of Being Cursed. - And he probably gets his secretary to deal
with it." (Terry Pratchett, Johnny and the Dead)