Arrays have always been my downfall in every language I’ve worked with, but I’m in a situation where I really need to create a dynamic array of multiple items in Rails (note – none of these are related to a model).
Briefly, each element of the array should hold 3 values – a word, it’s language, and a translation into English. For example, here’s what I’d like to do:
myArray = Array.new
And then I’d like to push some values to the array (note – the actual content is taken from elsewhere – although not a model – and will need to be added via a loop, rather than hard coded as it is here):
myArray[0] = [["bonjour"], ["French"], ["hello"]]
myArray[1] = [["goddag"], ["Danish"], ["good day"]]
myArray[2] = [["Stuhl"], ["German"], ["chair"]]
I would like to create a loop to list each of the items on a single line, something like this:
<ul>
<li>bonjour is French for hello</li>
<li>goddag is Danish for good day</li>
<li>Stuhl is German for chair</li>
</ul>
However, I’m struggling to (a) work out how to push multiple values to a single array element and (b) how I would loop through and display the results.
Unfortunately, I’m not getting very far at all. I can’t seem to work out how to push multiple values to a single array element (what normally happens is that the [] brackets get included in the output, which I obviously don’t want – so it’s possibly a notation error).
Should I be using a hash instead?
At the moment, I have three separate arrays, which is what I’ve always done, but I don’t particularly like – that is, one array to hold the original word, one array to hold the language, and a final array to hold the translation. While it works, I’m sure this is a better approach – if I could work it out!
Thanks!
Ok, let’s say you have the words you’d like in a CSV file:
Now in our program we can do the following:
After this code is executed, the words array had three items in it, each item is an array that is based off of our file.
Now we want to display these items.
This gives the following output:
Also, you didn’t ask about it, but you can access part of a given array by using the following:
This is telling ruby that you want to look at the first (Ruby arrays are zero based) element of the words array. Ruby finds that element ([“bonjour”, “French”, “hello”]) and sees that it’s also an array. You then asked for the second item ([1]) of that array and Ruby returns the string “French”.