2

Are there associative arrays in Ruby? Or associative arrays are just hashes for Ruby?

I heard in Ruby hashes and associative arrays aren't the same thing (like in some other languages).

So are there practical difference between associative arrays and hashes?

Jensky
  • 919
  • 3
  • 12
  • 26
  • There are no "associative arrays" in ruby. That's an idiosyncrasy of PHP. – Sergio Tulentsev Sep 18 '14 at 17:40
  • 1
    Yay, golden badge superpowers :) – Sergio Tulentsev Sep 18 '14 at 17:42
  • 1
    I voted to close this as a duplicate, but the down votes are really unnecessary. There's nothing wrong with being a newbie and asking a good question, just because others have asked it before. – jdl Sep 18 '14 at 17:42
  • 2
    @jdl: Technically, there *is* something wrong. Failure to search before asking. – Sergio Tulentsev Sep 18 '14 at 17:43
  • I agree with both of you, but it's a very straightforward search. I searched on "ruby associative arrays" and the original question was at the top of the list. Same when I used Google to search "ruby associative arrays site:stackoverflow.com". – Cary Swoveland Sep 18 '14 at 17:49
  • You're right and I found those post, but I read there: _"in Ruby they're a separate thing."_ And this was for me confusing that associative arrays and hashes are separated things in Ruby. So I just asked. Now I notice that that author was thinking about normal arrays not associative. – Jensky Sep 18 '14 at 17:57
  • @Jensky: yeah. he didn't say "associative arrays". But it could be misunderstood, I guess. – Sergio Tulentsev Sep 18 '14 at 18:01

1 Answers1

0

In Ruby there's a strict difference between Array and Hash:

array = [ 1, 2, 3, 4]
array[2]
# => 3

hash = { a: 1, b: 2, c: 3 }
hash[:a]
# => 1
hash[1]
# => nil

Unlike PHP, arrays are always a series of zero or more objects that have a particular ordering and hashes are key/value pairs.

tadman
  • 208,517
  • 23
  • 234
  • 262