So I have defined this class File
inside a module
and what I want to do is rewrite the self.parse
method so that it uses case
. I'm new to Ruby
so this is not straightforward for me. Also the method must contain in it's body no more than 8
lines of code. Any ideas how to do it? Also I asked it on Code Review
and they said it was off topic for them.
module RBFS
class File
attr_accessor :content
def initialize (data = nil)
@content = data
end
def data_type
case @content
when NilClass then :nil
when String then :string
when TrueClass , FalseClass then :boolean
when Float , Integer then :number
when Symbol then :symbol
end
end
def serialize
case @content
when NilClass then "nil:"
when String then "string:#{@content}"
when TrueClass , FalseClass then "boolean:#{@content}"
when Symbol then "symbol:#{@content}"
when Integer , Float then "number:#{@content}"
end
end
def self.parse (str)
arr = str.partition(':')
if arr[0] == "nil" then return File.new(nil) end
if arr[0] == "string" then return File.new(arr[2].to_s) end
if (arr[0] == "boolean" && arr[2].to_s == 'true') then return File.new(true) end
if (arr[0] == "boolean" && arr[2].to_s == 'false') then return File.new(false) end
if arr[0] == "symbol" then return File.new(arr[2].to_sym) end
return File.new(arr[2].to_i) if (arr[0] == "number" && arr[2].to_s.include?('.') == false)
return File.new(arr[2].to_f) if (arr[0] == "number" && arr[2].to_s.include?('.') == true)
end
end
end
Example how 'RBFS::File.parse' works:
RBFS::File.parse("string:"Hello world") => #<RBFS::File:0x1c45098 @content="Hello world"> #Tested in irb