user103220
user103220

Reputation: 55

Two quick Ruby questions

I've defined this class that contains an array and I have problems implementing the each method for it.


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

And also the second part is: How can I rewrite the following code, so that I have no return statements.


  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

Upvotes: 0

Views: 68

Answers (1)

tadman
tadman

Reputation: 211560

You just need to handle this with 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

As for the other thing, remember you can just condense your logic:

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

Since you're returning true, just return the evaluation of each bit of logic. Remember that there's an implicit return in Ruby, so it's not necessary to request one unless you're doing something more complicated than computing a binary condition.

Considering how you're basically testing against a variety of cases, best rewrite it as a case statement:

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

Upvotes: 4

Related Questions