From: Robert Klemme Date: 2012-02-08T07:09:55+09:00 Subject: Re: A better way? On Tue, Feb 7, 2012 at 10:00 PM, Dave Castellano wrote: > Hi, > > As I am learning to program, I am finding things I think can probably be > done in a better way.  The following code seems like something > programmers must run into all the time and I am wondering if there is a > better way to write the code in this situation.  I'm having fun and > trying to get better at this.... > >         if random_insert == 0 >            correct_answer_shuffled = "A" >          elsif random_insert == 1 >            correct_answer_shuffled = "B" >          elsif random_insert == 2 >            correct_answer_shuffled = "C" >          elsif random_insert == 3 >            correct_answer_shuffled = "D" >          elsif random_insert == 4 >            correct_answer_shuffled = "E" >          end > > Is there a better way?? If you want to pick a random item from a list Array#sample is the simplest: irb(main):011:0> a = %w{A B C D E} => ["A", "B", "C", "D", "E"] irb(main):012:0> a.sample => "E" irb(main):013:0> a.sample => "D" irb(main):014:0> a.sample => "E" irb(main):015:0> a.sample => "D" Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/