Barbared
Barbared

Reputation: 800

Ruby: blocks and yield

I run into this exercise about using blocks e then calling them with yield. It looks like this:

class Hero
  def initialize(*names)
    @names = names
  end
  def full_name
    # a hero class allows us to easily combine an arbitrary number of names
    # this is where yield should be
  end
end

def names
  heroes = [Hero.new("Christopher", "Alexander"),
            Hero.new("John", "McCarthy"),
            Hero.new("Emperor", "Joshua", "Abraham", "Norton")]
  # I have to use #map and #join to unify names of a single hero
end

Return value should look like this:

["Christopher Alexander", "John McCarthy", "Emperor Joshua Abraham Norton"]

I know how to use generally blocks and yield. I did very simple exercises before this but I can't solve this one.

Upvotes: 1

Views: 586

Answers (2)

nolith
nolith

Reputation: 613

This seems a strange request, but if you have to use yield and join as you write in the comments this is the solution:

class Hero
  def initialize(*names)
    @names = names
  end
  def full_name
    if block_given?
      yield @names
    else
      @names.join(' ')
    end
  end
end

def names
  heroes = [Hero.new("Christopher", "Alexander"),
            Hero.new("John", "McCarthy"),
            Hero.new("Emperor", "Joshua", "Abraham", "Norton")]
  heroes.map { |h| h.full_name { |name| name.join(' ') } }
end

Upvotes: 2

Reactormonk
Reactormonk

Reputation: 21690

Use Array#join. You don't need yield or any fancy stuff.

Upvotes: 3

Related Questions