0

I have seen this link about associated array in Ruby, and I know, it is completely like php.

But take a look at this piece of code:

x=[1,"Jef",:three]

it is clear that x[1]="jef", but the question is: What is the role of :three. I gussed it should be a key with a nill value, and i changed the code to this

x=[1,"Jef",:three,4]

and when i run it, I faced with this error:

no implicit conversion of Symbol into Integer (TypeError)

so what are the roles of : and three here?

Community
  • 1
  • 1
Sal-laS
  • 11,016
  • 25
  • 99
  • 169

2 Answers2

1

I think you're confusing arrays with hashes. In this particular example

x = [1,"Jef",:three,4]

incidently x[1] is equal to "Jef", but thats because element at 1st index of x is "jeff" (which should be obvious as x is an Array), not because every two elements are key value pairs as in a a Hash.

The error

no implicit conversion of Symbol into Integer (TypeError)

is probably because you tried something like x[:three], which is obviously invalid.

This could work if your x looks something like this.

x = { 1 => "Jef", :three => 4 }

Then x[:three] will result in desired result 4.

Remember Arrays and Hashes in Ruby are two different concepts.

:three is a Symbol which are essentially strings with few twists.

Suggestion : If you want to learn basic Ruby stuff you can read up on Rubymonk. I has great content.

Community
  • 1
  • 1
vjdhama
  • 4,878
  • 5
  • 33
  • 47
0

:three is a symbol and it's just a regular member of a regular array. Associative arrays in Ruby are something different and they're called hashes.

Marek Lipka
  • 50,622
  • 7
  • 87
  • 91