我是Ruby的;我看到有很多关于这个主题的问题......但找不到类似的问题,我收集到的多维数组在Ruby中并不存在。所以,我正在为一个虚构的数据集处理一个嵌套数组。我想通过迭代并为每个数组创建一个块是最好的方法(并在SO上证实了这一点)。我在另一篇文章中看到它推荐使用Narray库...这对字符串有用吗?我的第一个目标是打印出每个名字和最后一个感兴趣的区域。
staff_array = [
["paulBarry",
["programming", "networking", "security", "open source" ,"frameworks"]],
["chrisMuedec",
["testing", "safety systems", "formal systems", "programming languages"]],
["nigelwhite",
["graphics", "imaging", "programming","sign languages","trees"]],
["austinKinsella",
["networks", "wans", "programming", "macintosh", "digital photography"]],
["gerryMoloney",
["placement", "employment", "emerging systems", "webdevelopment"]
]
]
staff.each do |name_array|
# Iterate through the parent array, returning each element sequentially
name_array.each do |interest_element|
# Iterate through each element of the child array returned by the above parent iteration
puts {#name_array}+ name_array.each do |interest_element|[-1]
end
end
预期的输出将是:
Paulbarry: Frameworks
ChrisMuedec: Programming languages
Nigelwhite: Trees
AustinKinsella: Digital photography
GerryMoloney: Webdevelopment.
Ruby有嵌套数组。你可以用 []
办法 从0开始,无论嵌套级别如何。
array = [
[
['0.0.0', '0.0.1', '0.0.2'],
['0.1.0', '0.1.1', '0.1.2'],
['0.2.0', '0.2.1', '0.2.2'],
],
[
['1.0.0', '1.0.1', '1.0.2'],
['1.1.0', '1.1.1', '1.1.2'],
['1.2.0', '1.2.1', '1.2.2'],
],
[
['2.0.0', '2.0.1', '2.0.2'],
['2.1.0', '2.1.1', '2.1.2'],
['2.2.0', '2.2.1', '2.2.2'],
],
]
array[0][0][0] # => '0.0.0'
array[0][1][2] # => '0.1.2'
array[2][2][2] # => '2.2.2'
array.first.first.first # => '0.0.0'
array.last.last.last # => '2.2.2'
我的第一个目的是打印出每个名字和最后一个感兴趣的区域。
staff_array.each do |name, interests|
puts "#{name.sub(/./) { |m| m.upcase }}: #{interests.last.capitalize}"
end
输出。
PaulBarry: Frameworks
ChrisMuedec: Programming languages
Nigelwhite: Trees
AustinKinsella: Digital photography
GerryMoloney: Webdevelopment
也许从这第一步你就能推断出如何归纳出其他问题的答案。