返回布尔值而不是值,重新创建.select方法

时间:2018-12-17 07:35:53

标签: ruby boolean return-value

我正在尝试使用select循环和while重新创建yield方法。下面是我的代码:

def my_select(collection)
  count = 0
  newColl = []
  while collection.length > count
    if (collection[count] % 2 == 0)
      newColl.push(yield (collection[count]))
    end
    count += 1
  end
  newColl
end

当我运行以下命令时:

arr = [1, 2, 3, 4, 5]
my_select(arr) do |num|
  num.even?
end

我想要这个结果:

[2, 4]

但是我明白了:

[true, true]

我得到的是布尔值而不是实际值。

2 个答案:

答案 0 :(得分:2)

这是因为您推送了yield的结果(可以但不一定是布尔值)而不是实际的collection元素。您还应该根据yield返回的内容添加元素,例如:

element = collection[count]
newColl.push(element) if yield(element)

顺便说一句,我真的不明白为什么要在my_select方法中检查数字奇偶校验吗?没道理。

答案 1 :(得分:1)

将其更改为:

def my_select(collection)
  count = 0
  newColl = []
  while collection.length > count
    if (collection[count] % 2 == 0)
      result = yield collection[count] # yield first
      newColl.push(collection[count]) if result # then push to newColl if required
    end
    count += 1
  end
  newColl
end

arr = [1, 2, 3, 4, 5]
my_select(arr) {|num| num.even? }
#=> [2,4]

尽管,您的newColl集合在这里几乎没有用。

修改: 既然您提到过重新创建select,这可能是替代方法:

def my_select(collection)
  # it iterates on the collection and filters the item for which the block return true, at the end, I compact the collection to remove nils
  collection.map do |item|
    item if yield(item)
  end.compact
end

# or 
def my_select(collection)
  # start with a blank array
  coll = []
  # iterate on collection
  collection.each do |item|
    # insert all those items for which the block returns true by yield(item)
    coll << item if yield(item)
  end
  # return the array
  coll
end

arr = [1, 2, 3, 4, 5]
my_select(arr) {|num| num.even? }
#=> [2, 4]