(Beginner Question) Trying to extract elements from an embeded array

Hiya All,

I’ve been learning Ruby for about 2 weeks or so and had a go at putting
together proper bit of code, which I of course can’t get working :wink: Part
of my practice is to see how if…, while…, collect… and so on work.

In the code I have a set of embedded arrays with various strings. I then
generate a sequential number (0, 1, 2, etc) and a random number. With
those I index into each array in sequence using the sequence number, and
use the random number to pick a string at random from within them.

The output should be say “a, B” or “c, A”, etc.

I’ve been testing this in SciTe and get results of either [nil, nil] or
just “a, b” every time. Running it in Codepad I got [nil, nil] and [98,
98].

How the heck I can get nil, nil I don;t know, I’m guessing I’m getting
int/str mixed up here.

If anyone has a moment, could you look over the code I pasted at
Codepad. Any guidance on what I’m missing here technically and logically
would be greatly appreciated.

http://codepad.org/ohuMRrlE

Regards,

Dave.

Hi,

I made a minor change and got it to work. :slight_smile:

http://codepad.org/ybmXU9s3

Do you see the change I made, and do you see why it was needed?

Vikhyat K.

On Sat, Jan 21, 2012 at 3:40 AM, Dave E. [email protected] wrote:

Codepad. Any guidance on what I’m missing here technically and logically

The numbers are due to codepad using an older version of Ruby (1.8.6).
It
used to be that characters were represented by numbers known as an ascii
value.
If you look it up ASCII - Wikipedia you’ll see that the
character “a” correlates to the number 97, so on older Rubies, if you
said
“abc”[0] it would return 97. On newer Rubies (1.9.x), characters are
represented by strings of length 1, so “abc”[0] returns “a”.

Other than that, the reason you’re doing “a”[0] rather than
[“a”,“b”,“c”,“d”][0] is because you haven’t wrapped them in an array, as
Vikhyat showed in his updated version.

Also, consider using inspect instead of to_s when you’re trying to look
at
these values, inspect makes it easier to see what objects you’re dealing
with.
ie: puts "Array contents: " + extractedArray.inspect

Hiya Josh / Vikhyat,

Thanks for the quick replies. Incredible, so close yet so far away :slight_smile:

I finished my little ‘Insult Generator’ practice project and put it
here:
Ruby code - 17 lines - codepad (While…) and another version here:
Ruby code - 18 lines - codepad

Off to learn more!

Regards,

Dave.