Skip to content

Instantly share code, notes, and snippets.

@eladmeidar
Last active January 30, 2019 15:09
Show Gist options
  • Save eladmeidar/76a7228da9fc8a3cc68873879d4b4bd4 to your computer and use it in GitHub Desktop.
Save eladmeidar/76a7228da9fc8a3cc68873879d4b4bd4 to your computer and use it in GitHub Desktop.
Coding exercise
class String
module WidgetExceptions
class InvalidWidget < ArgumentError; end
end
def widget_inject(widgets = [])
self_with_widgets = self.clone
widgets.sort_by {|w| w[:position] }.reverse.each do |widget|
raise WidgetExceptions::InvalidWidget, "widget must be a hash, was #{widget.class.name}" unless widget.is_a?(Hash)
raise WidgetExceptions::InvalidWidget, "widget must have position and text keys" unless [:position, :text].all? {|k| widget.has_key?(k)}
self_with_widgets = self_with_widgets.insert(widget[:position], widget[:text])
end
return self_with_widgets
end
end
"Hello World".widget_inject([{position:2, text: "11"}, {position:4, text: "2222"}, {position: 6, text: "33"}]) #=> "He11ll2222o 33World"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment