Arrays 基于第一项的Ruby二维数组拒绝
我有一个二维数组Arrays 基于第一项的Ruby二维数组拒绝,arrays,ruby,Arrays,Ruby,我有一个二维数组 array = [["a first sentence of 6 words","Reference 1"],["another sentence that may be longer with 9 words","Reference 2"]] 我想删除第一个元素包含少于7个单词的所有条目,因此获取以下数组 [["another sentence that may be longer with 9 words","Reference 2"]] 我尝试了很多东西,包括
array = [["a first sentence of 6 words","Reference 1"],["another sentence that may be longer with 9 words","Reference 2"]]
我想删除第一个元素包含少于7个单词的所有条目,因此获取以下数组
[["another sentence that may be longer with 9 words","Reference 2"]]
我尝试了很多东西,包括
array.reject { |a| a.first.split.size < 7 }
我也试过了
array.reject { |a| a[0].split.size < 7 }
array.reject{a | a[0].split.size<7}
及
array.reject{| a | a.first.size<7}
但它似乎创建了一个无休止的循环,页面一直在加载,没有结果。有人能帮我找到正确的语法吗?看起来数组中的第一个元素是Fixnum。Fixnum上未定义拆分,因此出现错误 如果第一个项目的“到美国分割”小于7,则拒绝
array.reject { |a| a.first.to_s.split.size < 7 }
array.reject{a | a.first.to_.split.size<7}
您可以通过计算空格而不是创建中间数组来提高效率。您还可以通过使用并行赋值使其更具可读性。e、 g
arr = [
["a first sentence of 6 words","Reference 1"],
["another sentence that may be longer with 9 words","Reference 2"]
]
# split with no argument will separate on space and create an Array
# this means we can use `String#count` and look for the number of spaces that would
# create 7 words (e.g. 6 spaces)
# `#strip` will get rid of leading an trailing spaces so that `#count` will work like `#split`
arr.reject {|sentence,_ref| sentence.to_s.strip.count(' ') < 6 }
arr=[
[“第一句6个字”,“参考文献1”],
[“另一个可能更长的句子,包含9个单词”,“参考文献2”]
]
#不带参数的拆分将在空间上分离并创建数组
#这意味着我们可以使用'String#count'并查找需要的空格数
#创建7个单词(例如6个空格)
#“strip”将去掉前导空格和尾随空格,因此“count”的工作方式类似于“split”`
拒绝{句子,{u ref}句子到{u.strip.count('')<6}
array.reject{a | a.first.split.size<7}
应该可以工作;也许您正在其他地方更改数组的值?检查。看起来第一个元素之一是数组。Fixnum上未定义拆分,因此出现错误。array.reject{a | a.first.to_.split.size<7}只需将添加到a
之后的!a、 第一个是多余的,因为要
nil.to_s
返回一个空字符串。
array.reject { |a| a.first.to_s.split.size < 7 }
arr = [
["a first sentence of 6 words","Reference 1"],
["another sentence that may be longer with 9 words","Reference 2"]
]
# split with no argument will separate on space and create an Array
# this means we can use `String#count` and look for the number of spaces that would
# create 7 words (e.g. 6 spaces)
# `#strip` will get rid of leading an trailing spaces so that `#count` will work like `#split`
arr.reject {|sentence,_ref| sentence.to_s.strip.count(' ') < 6 }