Newbie
Newbie

Reputation: 1

A newbie learning RUBY: Needs to implement the wrap_array_elements method in class Formatter

Needs to implement a wrap_array_elements method that takes in an array and two args for the left and right side wrapping and returns a new array with a string containing the "wrapped" version of each element.

Example arguments: [5, 6, 7, 8, 9], "<<", ">>"

Should returns an array: ["<<5>>", "<<6>>", "<<7>>", "<<8>>", "<<9>>"]

class Formatter

    def wrap_array_elements(elements, left, right)
        @elements= elements
        @left = left
        @right = right
        formatted_array = Array.new
        formatted_array.push(elements.map {|element| @left + item + @right})
        puts "#{formatted_array}"
    end

end

Upvotes: 0

Views: 126

Answers (2)

spickermann
spickermann

Reputation: 106882

Or, instead of using string interpolation like in javiyu's solution, you can use Array.join:

class Formatter
  def wrap_array_elements(elements, left, right)
    elements.map { |element| [left, element, right].join }
  end 
end

Upvotes: 1

javiyu
javiyu

Reputation: 1474

It is much simpler than that, you just need to produce a new array from the original one with map.

class Formatter
  def wrap_array_elements(elements, left, right)
    elements.map {|element| "#{left}#{element}#{right}"}
  end
end

Upvotes: 1

Related Questions