如何使用Ruby以有效的方式从字符串中获取所需的格式化哈希?

前端之家收集整理的这篇文章主要介绍了如何使用Ruby以有效的方式从字符串中获取所需的格式化哈希?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当字符串以下面的格式出现时,我想以特定格式哈希:

给定字符串:

str = 'A
A = B
A = B = C
A = B = D
A = E = F
G = H
G = I
G = J'

#进入这样的哈希(必需的哈希模式):

{
  "A" => {
    "B" => {
      "C" => nil,"D" => nil
    },"E" => {
      "F" => nil
    },},"G" => {
     "H" => nil,"I" => nil,"J" => nil
  }
}

我尝试了很多方法,但这是最接近的:

output = Hash.new
line_hash = Hash.new
str.each_line do |line|
  arr = line.split("=")
  e = arr.first.strip
  line_hash[e] = {}
  arr.each_with_index do |ele,i|
    break unless arr[i+1]
    line_hash[ele.strip] = arr[i+1] unless output.keys.include?(ele.strip)
  end
  output[e] = line_hash unless output.keys.include?(e)
end

解决方法

str = "A\nA = B\nA = B = C\nA = B = D\nA = E = F\nG = H\nG = I\nG = J"

curr = h = {}

str.each_line { |l| 
  l.chomp.split(/\s*=\s*/m).each { |c| 
    curr = curr[c] ||= {}; 
  }
  curr = h 
}

puts h
# => {
#  "A" => {
#    "B" => {
#      "C" => {},#      "D" => {}
#    },#    "E" => {
#      "F" => {}
#    }
#  },#  "G" => {
#    "H" => {},#    "I" => {},#    "J" => {}
#  }
# }

我希望你能原谅我留下空的哈希值而不是叶子上的空值,以便清楚地解决问题.

要使叶子无效:

def leaves_nil! hash
   hash.each { |k,v| v.empty? ? hash[k] = nil : leaves_nil!(hash[k]) }  
end
原文链接:https://www.f2er.com/ruby/268554.html

猜你在找的Ruby相关文章