How can one parse this in Yaml?

2019-08-16 14:54发布

Suppose I have this example :

Example:
  number:
    cuarenta
    cuarenta y uno
    cuarenta y dos
    cuarenta y tres
    cuarenta y cuatro
    cuarenta y cinco
    cuarenta y seis
    cuarenta y siete
    cuarenta y ocho
    cuarenta y nueve

And I'd like to parse this so that I have each of those numbers together like "cuaranta y nueve". I'm having trouble visualizing how to do that since in YAML, you're turned a string associated with "noun".

My yaml parser looks like this :

  File.open(Rails.root + 'lib/words/yamlicious.yml', 'r') do |file|
    YAML::load(file).each do |topic, word_types|
      temp_topic = Topic.create! name: topic
      temp_words = word_types.map{|type, words| words.split(' ').map {|word| Word.create type: type, word: word, topics: [temp_topic] } }
      temp_topic.words << temp_words
    end
  end

Notice the split part would ruin that because then I would get a word created per my example as three words "cuarenta", "y", and "uno".

1条回答
我想做一个坏孩纸
2楼-- · 2019-08-16 15:37

To preserve newlines, you have to use the pipe character:

Example:
  number: |
    cuarenta
    cuarenta y uno
    cuarenta y dos
    …

Now you can split("\n")

查看更多
登录 后发表回答