Victor Xiong
Victor Xiong

Reputation: 325

How to make dynamic key names in YAML file

I want to make dynamic key names and values in YAML file so it can save some space.

For example:

KID(\d+)_AGE: &kid(params)_age
  kid(params): "18"

So the expected result should be:

KID1_AGE: &kid1_age
  kid1: "18"

So the key is dynamic whenever I put KID1_AGE, KID2_AGE, they will pick up this same hash.

Any suggestions on how to obtain this? This is primarily used in Ruby.

Thank you.

Upvotes: 3

Views: 5101

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

You can't use a string that looks like a regex pattern as a key, and expect it to act like a regex. YAML, and Ruby, don't work that way. You also can't use regex patterns as the keys of a hash, and then throw a string at the hash and have the keys automatically match and return the associated values. Hashes and Ruby don't work that way.

You could create keys that match a pattern, and then have Ruby walk through the hash returned by YAML, looking for keys that match, but that's not going to save you any space, based on what you say your objective is.

Use YAML's ability to use aliases and anchors as fully as possible. They can keep the YAML file smaller, while still providing access to the values you need once the file is parsed.

Upvotes: 2

maček
maček

Reputation: 77778

If you're using Rails, the file is being parsed with ERb first

# foo.yaml

my_random: <%= Random.rand(1..100) %>

So you could do something like

<% 100.times do |n| %>
<%= "KID#{n}_AGE: &kid#{n}_age" %>
<% end %>

This feels pretty code smelly though. You should probably explain your overall objective rather than how you want to implement it.

Upvotes: 3

Related Questions