两个快速的Ruby问题

时间:2014-10-23 20:10:44

标签: ruby

我已经定义了这个包含数组的类,但我在实现each方法时遇到了问题。


class Number
include Enumerable
def initialize
  @array = []
end

# for some reason this doesn't work on the the @array members
# when calling each
# and I also have to return an Enumerable if no block is given
def each &block
  @array.each do |number| 
  block.call (number) 
 end
end

第二部分也是:如何重写以下代码,以便我没有return语句。


  def determine number # @sing is a member of another class I have
    return true if (@sign == :negative && number < 0)
    return true if (@sign == :positive && number > 0)
    return true if (@sign == :non_negative && number >= 0)
    true if (@sign == :non_positive && number <= 0)
  end

1 个答案:

答案 0 :(得分:4)

您只需要使用block_given?处理此问题:

class Number
  include Enumerable

  def initialize
    @array = []
  end

  def each
    if (block_given?)
      @array.each do |number|
        yield(number)
      end
    else
      @array.each
    end
  end
end

至于另一件事,记住你可以简化你的逻辑:

def test?
  (...) || (...) || (...)
end

由于您要返回true,只需返回每个逻辑位的评估。请记住,Ruby中有一个隐式return,所以除非你做的事情比计算二元条件更复杂,否则没有必要请求。

考虑到你基本上如何针对各种情况进行测试,最好将其重写为case语句:

def determine(number)
  case (@sign)
  when :negative
    number < 0
  when :positive
    number > 0
  when :non_negative
    number >= 0
  when :non_positive
    number <= 0
  else
    true
  end
end