数组中的双索引号(Ruby)

时间:2015-01-31 06:11:32

标签: ruby

数组计数如下:

counts = ["a", 1]

这是什么:

counts[0][0]

参考?

我以前只见过这个:

array[idx] 

但从未这样:

array[idx][idx] 

其中idx是整数。

这是以前代码段的完整代码:

  def num_repeats(string) #abab
    counts = [] #array

    str_idx = 0 
    while str_idx < string.length #1 < 4
      letter = string[str_idx] #b

      counts_idx = 0 
      while counts_idx < counts.length #0 < 1
        if counts[counts_idx][0] == letter #if counts[0][0] == b
          counts[counts_idx][1] += 1
          break
        end
        counts_idx += 1
      end

      if counts_idx == counts.length #0 = 0
        # didn't find this letter in the counts array; count it for the
        # first time
        counts.push([letter, 1]) #counts = ["a", 1]
      end

      str_idx += 1
    end

    num_repeats = 0
    counts_idx = 0
    while counts_idx < counts.length
      if counts[counts_idx][1] > 1
        num_repeats += 1
      end

      counts_idx += 1
    end

    return counts
  end

2 个答案:

答案 0 :(得分:0)

声明

arr[0]

获取数组arr的第一项,在某些情况下,它也可能是一个数组(或另一个可索引对象),这意味着您可以获取该对象并从该数组中获取一个对象:

# if arr = [["item", "another"], "last"]
item = arr[0]
inner_item = item[0]
puts inner_item # => "item"

这可以缩短为

arr[0][0]

因此任何包含可索引对象的二维数组或数组都可以这样工作,例如带有一串字符串:

arr = ["String 1", "Geoff", "things"]
arr[0] # => "String 1"
arr[0][0] # => "S"
arr[1][0] # => "G"

答案 1 :(得分:0)

嵌套索引

a = [ "item 0", [1, 2, 3] ]
a[0] #=> "item 0"
a[1] #=> [1, 2, 3]
a[1][0] #=> 1

由于索引1处的值是另一个数组,因此您也可以对该值使用索引引用。

修改

抱歉,我没有仔细阅读原始问题。有问题的数组是

counts = ["a", 1]

在这种情况下,counts[0]返回"a",因为我们可以使用索引来引用字符串的字符,所以字符串"a"中的第0个索引只是"a"。< / p>

str = "hello"
str[2] #=> "l"
str[1] #=> "e"