Ruby 做题:Bag#every?

chenge · 2014年04月25日 · 最后由 chenge 回复于 2014年04月25日 · 2605 次阅读

大伙儿很有兴趣,再来一题,6yku。

We have an awesome, custom collection class, Bag, which already has implemented an #each for traversing its items and #count for counting the items. New requirements come in for the project to check arbitrary conditions regarding data inside of a Bag.

We were just about to break out the trusty old #each hammer, when we realize there might be an better/easier/cleaner way. Spotting an abstraction waiting to happen, we decide implement a new method, #every?, to make sure that every item in a Bag matches the condition.

The #every? method needs to receive a block to run some test against every item. If every test passes, it returns true. If any of the tests fail, it returns false. Empty bags should pass all tests.

It also has a shorthand variation for our lazy friends. If you do not pass a block to #every, it tests the truthiness of the items themselves.

class Bag

  # already implemented:
  #   #each
  #   #count


Examples:

bag = Bag.new(:surefire, :tests)
bag.every? { true } # => true
bag.every? { false } # => false

bag = Bag.new(1,2,3,4)
bag.every? { |num| num > 0 } # => true
bag.every? { |num| num.odd? } # => false

bag = Bag.new(:code, :wars)
bag.every? # => true

bag = Bag.new(:cat, :+, :roomba, nil, :profit!)
bag.every? # => false

反正已经出过一次洋相了不介意再出一次...

def every?
  self.each do |item|
    if block_given?
      return false unless yield item
    else
      return false unless item
    end
  end
  true
end

#1 楼 @blacktulip 谢谢,学习了。

def every?
    each do |item|
      return false unless block_given? ? yield(item) : item
    end

    return true
  end

这个思路类似

直接贴题目也就罢了,要每次都我来给你格式化帖子嘛?

#3 楼 @lgn21st 单行代码不用格式吧

需要 登录 后方可回复, 如果你还没有账号请 注册新账号