.

arrays in ruby on rails



Posted on

learning arrays and got confused by what transposition is. In genetics, it means genes replacing other genes, but the number based example on the official documentation wasn’t meshing well with dyslexia and end-of-day tiredness. I just saw numbers. It looked the same.

I started swapping out numbers for names from different fandoms and eventually came up with this to help me remember how it works.

a = [["Jaime Lannister","Cersi Lannister","Tyrion Lannister"], ["Buffy","Spike", "Willow"], ["Harry Potter","Bellatrix Lestrange","Harmanie Granger"]]


print "we're having dinner with "
puts a.transpose[(rand(a.length + 1))]
print " tonight. Should be interesting."

This outputs a character from each fandom randomly coming to dinner.

I had problems getting the last embedded array to show using squence numbers- until I remembered computers don’t count at 1.  Swapping 3 for 2 worked.

But I wanted to be surprised by who was coming! I wanted to use the random class.

and using rand with the number of 2, wasn’t working.

This is because the value of rand is between 0 but less than the number entered, so using [rand (2)] was why Tyrion never graced our imaginary table.

(rand(a.length + 1)) is for me to help me remember that in future.


by

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Stay in touch

Get more informal notes, summaries, and screenshots, on the business of making digital products and running a calm creative business by signing up to my newsletter