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…
Il giorno Wed, 8 Feb 2012 06:00:09 +0900
Dave C. [email protected] ha scritto:
elsif random_insert == 1
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:
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.
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.
As I am learning to program, I am finding things I think can probably be
done in a better way.
Congratulations! In addition to what the others have said, to simply
solve the current problem, this attitude is a significant milestone in
becoming a good programmer!