我想将此文本字符串转换为哈希,以便根据用户输入创建页面。
Home
About
- News
-- Local News
-- Global News
- Who We Are
Product
这只是一个例子,但我想把它转换成我可以迭代的多维哈希。我想为用户创建一种在CMS中创建页面的简便方法。
我玩过分裂字符串和正则表达式,但我没有做到这一点。
非常感谢任何帮助!
答案 0 :(得分:2)
看起来Yaml会成为你的朋友。看看Yaml.load。 test.yml:
"Home":
"About":
"News":
"Local News":
"Global News":
"Who We Are":
"Products":
IRB
require 'yaml'
YAML.load(File.open('test.yml'))
=> {"home"=>{"About"=>{"News"=>{"Local News"=>nil, "Global News"=>nil, "Who We Are"=>nil}}, "Product"=>nil}}
答案 1 :(得分:0)
这是我的尝试。我完全承认它看起来并不惯用,并且ruby stdlib中可能有一个可以替代它的单线程。但是,嘿,至少这有效:)
所以,基本的想法是:
代码:
txt = <<-TXT
Home
About
- News
-- Local News
-- Global News
- Who We Are
Product
TXT
def lines_to_hash lines
res = {}
last_level = 0
parent_stack = [res]
last_line = nil
lines.each do |line|
cur_level = line.scan('-').length
if cur_level > last_level
parent_stack << parent_stack.last[last_line]
elsif cur_level < last_level
parent_stack.pop
end
clean_line = line.gsub(/^[-\s]+/, '')
parent_stack.last[clean_line] = {}
last_line = clean_line
last_level = cur_level
end
res
end
res = lines_to_hash(txt.split("\n"))
res # => {"Home"=>{},
# "About"=>{"News"=>{"Local News"=>{}, "Global News"=>{}},
# "Who We Are"=>{}},
# "Product"=>{}}
如果有人想出一个单行,我将奖励+100代表赏金:)
答案 2 :(得分:0)
txt = <<-TXT
Home
About
- News
-- Local News
-- Global News
- Who We Are
Product
TXT
def hashify s
Hash[s.split(/^(?!-)\s*(.*)/).drop(1).each_slice(2).map{|k, v| [k, hashify(v.to_s.strip.gsub(/^-/, ""))]}]
end
hashify(txt)
# =>
# {
# "Home" => {},
# "About" => {
# "News" => {
# "Local News" => {},
# "Global News" => {}
# },
# "Who We Are" => {}
# },
# "Product" => {}
# }
答案 3 :(得分:0)
@Sergio:这是一个单行! (不可否认,为了“清晰”,我将它分成了几行)
@ lt-matt8:如果您真的使用了这个,那么我对以后阅读您的代码的任何人的理智都不负任何责任:)
text = <<-TEXT
Home
About
- News
-- Local News
-- Global News
- Who We Are
Product
TEXT
hash = text.lines.each_with_object([{}]) {|item, levels|
item.match(/(-*)\s*(.*)/).captures.tap {|level, title|
levels[level.size][title] = (levels[level.size + 1] = {})
}
}.first
# => {"Home"=>{}, "About"=>{"News"=>{"Local News"=>{}, "Global News"=>{}}, "Who We Are"=>{}}, "Product"=>{}}