質問

I'm trying to recreate Enumerable's count method as found in "Projects: Advanced Building Blocks".

The definition in the Ruby docs is that count

"Returns the number of items in enum through enumeration. If an argument is given, the number of items in enum that are equal to item are counted. If a block is given, it counts the number of elements yielding a true value."

What exactly is the default argument though?

The way I approached this so far is as follows: The parameter is set to something when no argument is passed so:

Case, when self is not a string:

  1. when argument given and block given (eg. [1,2,3].count(3) { |x| x == 3 }): returns warning and count of the argument.

  2. when argument given and no block (eg. [1,2,3].count(3)): returns count of the argument.

  3. when no argument and no block (eg. [1,2,3].count): returns size of the instance.

  4. else (no argument given and block given) (eg. [1,2,3].count { |x| x == 3 }: returns count based on specifications given in block.

The two questions I have are basically:

  • What is the default argument for count?
  • What is the global variable used in warning?

Here's my code:

module Enumerable

  def my_count arg='default value'
    if kind_of? String
      # code
    else # I think count works the same way for hashes and arrays
      if arg != 'default value' 
        count = 0
        for index in 0...size
          count += 1 if arg == self[index]
        end
        warn "#{'what goes here'}: warning: block not used" if block_given?
        count
      else
        return size if arg == 'default value' && !block_given?
        count = 0
        for index in 0...size
          count += 1 if yield self[index]
        end
        count
      end
    end
  end

end
役に立ちましたか?

解決

Don't use a default argument. Use *args to collect all the arguments into an array.

def my_count(*args, &block)

  if args.length == 1 && !block_given?
    # use args[0]
  elsif args.length == 1 && block_given?
    # use block
  elsif args.length == 0 && !block_given?
    # no argument/block
  else
    # raise error
  end
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top