Ruby函数获取数组中的特定项并动态获取嵌套数据

Ruby function to get specific item in array and dynamically get nested data

如果我有一个看起来像这样的哈希数组

array = [{
  name: 'Stan',
  surname: 'Smith',
  address: {
    street: 'Some street',
    postcode: '98877',
    #...
  }
}, {
  #...
}]

你能写一个函数来获取数组中的特定项,迭代它并动态检索随后的嵌套数据吗?

这个例子不起作用,但希望能更好地解释我的问题:

def getDataFromFirstItem(someVal)
  array(0).each{ |k, v| v["#{ someVal }"] }
end

puts getDataFromFirstItem('name')
# Expected output: 'Stan'

对于上下文,我正在尝试创建一个 Middleman 助手,这样我就不必每次在模板中使用它时都循环访问只有一个项目的特定数组。该项目(哈希)包含大量全局站点变量。数据来自Contentful,其中一切都是一个条目数组。

请试试这个

array = [{
  name: 'Stan',
  surname: 'Smith',
  address: {
    street: 'Some street',
    postcode: '98877',
    #...
    }
  },
  {
    name: 'Nimish',
    surname: 'Gupta',
    address: {
      street: 'Some street',
      postcode: '98877',
      #...
    }
  }
]


def getDataFromFirstItem(array, someVal)
  array[0][someVal]
end

#Run this command
getDataFromFirstItem(array, :name) # => 'Stan'

#Please notice I send name as a symbol instead of string because the hash you declared consists of symbol keys

#Also if you want to make a dynamic program that works on all indexes of an array and not on a specific index then you can try this

def getDataFromItem(array, index, someVal)
  if array[index]
    array[index][someVal]
  end
end

getDataFromItem(array, 0, :name) # => Stan
getDataFromItem(array, 1, :name) # => Nimish
getDataFromItem(array, 2, :name) # => nil

希望这有效,如果您仍然遇到任何问题,请告诉我

从 ruby 2.3 及更高版本开始,您可以使用 Array#dig and Hash#dig 这两个

Extracts the nested value specified by the sequence of idx objects by calling dig at each step, returning nil if any intermediate step is nil.

array = [{
  name: 'Stan',
  surname: 'Smith',
  address: {
    street: 'Some Street',
    postcode: '98877'
  }
}, {
}]

array.dig(0, :name)               # => "Stan"
array.dig(0, :address, :postcode) # => "98877"
array.dig(0, :address, :city)     # => nil
array.dig(1, :address, :postcode) # => nil
array.dig(2, :address, :postcode) # => nil