'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
Solution 1:[1]
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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | javiyu |
| Solution 2 | Stefan |
