From: Chad Perrin Date: 2012-02-08T06:22:13+09:00 Subject: Re: A better way? On Wed, Feb 08, 2012 at 06:00:09AM +0900, 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?? One option: correct_answer_shuffled = case random_insert when 0 then 'A' when 1 then 'B' when 2 then 'C' when 3 then 'D' when 4 then 'E' end Another option: answers = %w{A B C D E} correct_answer_shuffled = answers[random_insert] I could offer other suggestions as well, but they would involve making assumptions about your code outside of the snippet you provided, and as such might not solve the problem you're actually trying to solve as demonstrated explicitly by your sample code. -- Chad Perrin [ original content licensed OWL: http://owl.apotheon.org ]