Ruby : Associative Arrays

前端 未结 3 859
难免孤独
难免孤独 2020-12-13 23:57

Does Ruby on rails have associative arrays?

For eg:

   a = Array.new
   a[\"Peter\"] = 32
   a[\"Quagmire\"] = \'asdas\'

What is

相关标签:
3条回答
  • 2020-12-14 00:05

    For completeness, it's interesting to note that Ruby does provide Array#assoc and Array#rassoc methods that add "hash like lookup" for an array of arrays:

    arr = [
      ['London', 'England'],
      ['Moscow', 'Russia'],
      ['Seattle', 'USA']
    ]
    
    arr.assoc('Seattle') #=> '['Seattle', 'USA']
    arr.rassoc('Russia') #=> ['Moscow', 'Russia']
    

    Keep in mind that unlike a Ruby hash where lookup time is a constant O(1), both assoc and rassoc have a linear time O(n). You can see why this is by having a look at the Ruby source code on Github for each method.

    So, although in theory you can use an array of arrays to be "hash like" in Ruby, it's likely you'll only ever want to use the assoc/rassoc methods if you are given an array of arrays - maybe via some external API you have no control over - and otherwise in almost all other circumstances, using a Hash will be the better route.

    0 讨论(0)
  • 2020-12-14 00:10

    Unlike PHP which conflates arrays and hashes, in Ruby (and practically every other language) they're a separate thing.

    http://ruby-doc.org/core/classes/Hash.html

    In your case it'd be:

    a = {'Peter' => 32, 'Quagmire' => 'asdas'}
    

    There are several freely available introductory books on ruby and online simulators etc.

    http://www.ruby-doc.org/

    0 讨论(0)
  • 2020-12-14 00:13

    Use hashes, here's some examples on how to get started (all of these do the same thing, just different syntax):

    a = Hash.new
    a["Peter"] = 32
    a["Quagmire"] = 'asdas'
    

    Or you could do:

    a = {}
    a["Peter"] = 32
    a["Quagmire"] = 'asdas'
    

    Or even a one liner:

    a = {"Peter" => 32, "Quagmire" => 'gigity'}
    
    0 讨论(0)
提交回复
热议问题