From: Stefano Crocco Date: 2012-02-08T06:14:57+09:00 Subject: Re: A better way? Il giorno Wed, 8 Feb 2012 06:00:09 +0900 Dave Castellano ha scritto: > 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?? > > Thanks... > > Dave > You can create a hash having the possible values of random_insert as keys and the corresponding values you want to assign to correct_answer_shuffled as values: possible_answers = {0 => "A", 1 => "B", 2 => "C", 3 => "D", 4 => "E"} correct_answer_shuffled = possible_answers[random_insert] Given that the values of random_insert are positive integers, you can also use an array instead of a hash: possible_answers = ["A","B", "C", "D", "E"] correct_answer_shuffled = possible_answers[random_insert] You could also use a case expression, which gives code more similar to what you wrote: 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 This is best used when you have to perform different operations depending on the value of random_insert, rather than using a different, fixed value. In this case, an array or hash are better solution. I hope this helps Stefano