我想通过仅读取一次字符串(O(n)时间复杂度)从Ruby中的字符串中提取一些信息。
这是一个例子:
字符串如下所示:-location here -time 7:30pm -activity biking
我有一个 Ruby 对象,我想用这个信息填充。所有关键字都是已知的,它们都是可选的。
def ActivityInfo
_attr_reader_ :location, :time, :activity
def initialize(str)
@location, @time, @activity = DEFAULT_LOCATION, DEFAULT_TIME, DEFAULT_ACTIVITY
# Here is how I was planning on implementing this
current_string = ""
next_parameter = nil # A reference to keep track of which parameter the current string is refering to
words = str.split
while !str.empty?
word = str.shift
case word
when "-location"
if !next_parameter.nil?
next_parameter.parameter = current_string # Set the parameter value to the current_string
current_string = ""
else
next_parameter = @location
when "-time"
if !next_parameter.nil?
next_parameter.parameter = current_string
current_string = ""
else
next_parameter = @time
when "-activity"
if !next_parameter.nil?
next_parameter.parameter = current_string
current_string = ""
else
next_parameter = @time
else
if !current_string.empty?
current_string += " "
end
current_string += word
end
end
end
end
所以基本上我只是不知道如何让一个变量成为另一个变量或方法的引用,这样我就可以将它设置为一个特定的值。或者也许还有另一种更有效的方法来实现这一目标?
谢谢!