Paul Hoffer
Paul Hoffer

Reputation: 12906

Ruby - chaining methods and returning array

I have some methods for a class which return arrays like ["1", "3", "2", "6", "2"]. It is ok that these are string arrays, not numeric. I have another method that takes an array, and turns it into a single string like this 1 3 2 6 2.

class Turn
  def initialize
    @rolls = 1
    @dice = []
  end

  def roll
    @roll = []
    x = 5 - @dice.length
    x.times do |i|
      @roll[i] = rand(6) + 1
    end
    @roll  # ["1", "3", "2", "6", "2"]
  end

  def show
    @dice  # ["1", "3", "6"]
  end

  def line(something)
    temp = ""
    something.each do |x|
      temp << x + " "
    end
    puts temp   # "1 3 6 " or "1 3 2 6 2 "
  end
end

Then I want to be able to chain methods together so I could do

first = Turn.new
first.roll.line
first.show.line

However, I really don't know how to do this, and I haven't been able to find how online. I have seen self get returned, but I can't really figure out what it does. The code in the line method works if I move it into another method, so the problem is really just dealing with the chaining and returning.

If someone could not only help with code, but with how chaining works with regards to return values and how returning self works, that would be awesome.

Thank you!

Upvotes: 2

Views: 2481

Answers (1)

Zargony
Zargony

Reputation: 10155

Since your #roll and #show methods return an array, you'd need to define a method Array#line to actually be able to do first.roll.line.

Btw, there's already Array#join which also joins array elements together to a string, just like your #line method, so you could as well use first.roll.join(' ') and get rid of your #line method.

Upvotes: 2

Related Questions