Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Ruby数组中测试数据_Ruby_Arrays - Fatal编程技术网

在Ruby数组中测试数据

在Ruby数组中测试数据,ruby,arrays,Ruby,Arrays,假设我有一个Ruby中的数组 array = [["bob", 12000, "broke", "ugly"], ["kelly", 50000, "rich", "attractive"]] 每个子阵列只是一个记录。在某些条件下,测试每个子阵列的某些元素(例如 每个数组中的第0个元素都是字符串吗 每个数组中的第二个元素都是整数吗 谢谢 尝试使用all?: all_match = array.all? {|inner_array| inner_array[0].k

假设我有一个Ruby中的数组

array = [["bob", 12000, "broke", "ugly"],
         ["kelly", 50000, "rich", "attractive"]]
每个子阵列只是一个记录。在某些条件下,测试每个子阵列的某些元素(例如

  • 每个数组中的第0个元素都是字符串吗
  • 每个数组中的第二个元素都是整数吗

谢谢

尝试使用
all?

all_match = array.all? {|inner_array|
    inner_array[0].kind_of?(String) && inner_array[1].kind_of?(Fixnum)
}

由于您提到了每个元素,惯用的方法是使用
all?
enumerable。像这样:

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
}

是一个很好的起点。

我不想删除元素。我只想在处理数组之前验证它的完整性。您在第一句中说
any?
,但代码示例使用
all?