仅当第一个元素满足条件时,如何删除数组的起始元素?

时间:2017-05-22 18:46:08

标签: arrays ruby remove-if

在Ruby中,假设我有一系列ordreed,唯一数字

public function __construct()
    {
       $this->money= 5000;
    }

如果数组的第一个元素为零,如何从数组的开头删除连续的所有元素,从零开始?也就是说,在上面的例子中,我想删除“0”,“1”和“2”,留下我

[0, 1, 2, 4, 6, 8, 10]

但如果我的数组是

[4, 6, 8, 10]

我希望数组不变,因为第一个元素不是零。

6 个答案:

答案 0 :(得分:4)

您可以混合使用drop_whilewith_index来删除第一个匹配的元素:

[0, 1, 2, 4, 6, 8, 10].drop_while.with_index{|x, i| x == i}
# [4, 6, 8, 10]

[1, 1, 2, 4, 6, 8, 10].drop_while.with_index{|x, i| x == i}
# [1, 1, 2, 4, 6, 8, 10]

请注意,第二个和第三个元素在第二个示例中不会被删除,即使它们等于它们的索引。

答案 1 :(得分:3)

删除元素,只要它们等于它们的索引:

a=a.drop_while.with_index{|e,i| e==i}

答案 2 :(得分:2)

你可以这样做:

x = -1
while my_array.first == x + 1 do
  x = my_array.shift
end

请注意,array.shift与array.pop相同,只是它从数组的开头起作用。

答案 3 :(得分:2)

听起来你正试图删除与idx匹配的实体(前提是第一个idx为0)。试试这个:

   if array.first == 0 
      new_array = array.reject.each_with_index{ |item, idx| item == idx } 
  end

虽然这只适用于有序数字的有序数组,但如果您不确定它们是否包含在内:array = array.sort.uniq

答案 4 :(得分:0)

如果我理解你的话,那么它可能是一种可能的解决方案:

def foo(array)
  if array.first.zero?
    array.keep_if.with_index { |e, ind| e != ind }
  else
    array
  end
end

> foo([0, 1, 2, 5, 6, 7])
#=> => [5, 6, 7]
> foo([1, 2, 3])
#=> [1, 2, 3]

答案 5 :(得分:-1)

简短形式:

a[0] == 0 ? a[3..-1] : a

更长的形式:

if a.first == 0
  a[3..(a.size)]
else
  a
end
相关问题