假设我在 Ruby 中有一个数组,
array = [["bob", 12000, "broke", "ugly"],
["kelly", 50000, "rich", "attractive"]]
每个子数组只是一条记录。在某些条件下测试每个子数组的某些元素的语法上最优雅的结构是什么,例如
- 每个数组中的第零个元素都是字符串吗?
- 每个数组中的第二个元素都是整数吗?
谢谢!
最佳答案
由于您提到了每个元素,惯用的方法是使用 all?
可枚举。像这样:
array = [["bob", 12000, "broke", "ugly"],
["kelly", 50000, "rich", "attractive"]]
array.all? { |element|
# check whatever you would like to check
# check if zeroth element is String or not
element.first.is_a?(String) # this would mean that you are assuming element is a collection, since first generally works on a collection
}
Enumerable
是一个很好的起点。
关于ruby - 在 Ruby 数组中测试数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4457332/