【发布时间】:2014-11-05 23:53:53
【问题描述】:
所以我在module 中定义了这个class File,我想做的是重写self.parse 方法,以便它使用case。我是Ruby 的新手,所以这对我来说并不简单。此外,该方法的主体中包含的代码行数不得超过8。任何想法如何做到这一点?我也在Code Review 上问过,他们说这对他们来说是题外话。
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
'RBFS::File.parse' 的工作原理示例:
RBFS::File.parse("string:"Hello world") => #<RBFS::File:0x1c45098 @content="Hello world"> #Tested in irb
【问题讨论】:
标签: ruby if-statement case