Skip to content

Instantly share code, notes, and snippets.

@robertomiranda
Forked from stevebartholomew/gist:1feab9d6fa5128f618c4
Last active June 22, 2017 12:47
Show Gist options
  • Save robertomiranda/90be9269fde72024e288c3fa5914c234 to your computer and use it in GitHub Desktop.
Save robertomiranda/90be9269fde72024e288c3fa5914c234 to your computer and use it in GitHub Desktop.
Ruby refactoring exercise
class Array
def to_annotated_xml(root)
output = "<#{root}>"
each do |i|
if i.is_a?(Fixnum)
output << "<number>#{i}</number>"
elsif i.is_a?(String)
if i.match(/@/)
output << "<email>#{i}</email>"
else
output << "<string>#{i}</string>"
end
else
output << "<value>#{i}</value>"
end
end
output << "</#{root}>"
end
end
p [1, "Stephen", "stephenb@reallyenglish.com"].to_annotated_xml("person")
class Object
def to_annotated_xml
"<value>#{self}</value>"
end
end
class String
def to_annotated_xml
tag = self.match(/@/) ? 'email' : 'string'
"<#{tag}>#{self}</#{tag}>"
end
end
class Fixnum
def to_annotated_xml
"<number>#{self}</number>"
end
end
class Array
def to_annotated_xml(root)
output = "<#{root}>"
each do |i|
output << i.to_annotated_xml
end
output << "</#{root}>"
end
end
p [1, "Stephen", "stephenb@reallyenglish.com"].to_annotated_xml("person")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment