Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add :stringify_names option to convert symbol keys to string for dumping #621

Merged
merged 1 commit into from Jan 18, 2024

Conversation

fnordfish
Copy link
Contributor

When dumping larger and/or nested Hashes, it would be useful to let Psych treat symbol keys as string keys to avoid building a new hash with string keys, just for the sake of dumping.

:stringify_names for dumping is conceptually the reverse of :symbolize_names for loading:

yaml = "---\nfoo: bar\n"
Psych.dump(Psych.load(yaml, symbolize_names: true), stringify_names: true) == yaml # => true

@fnordfish
Copy link
Contributor Author

Did a small benchmark, comparing symbolize_names: true vs. manual deep stringify keys: https://gist.github.com/fnordfish/4b22aed6281800897e56399d6c53c0be

While overall performance gains seem to be within margin of error, memory usage is consistently down.

Copy link
Member

@tenderlove tenderlove left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like a fine feature, but is the option name the right thing? It's stringify_names, but that seems pretty ambiguous from the reader's perspective. Maybe stringify_symbol_keys or something?

@fnordfish
Copy link
Contributor Author

I'm absolutely not married to the name.

But just for the sake of the argument, symbolize_names does also only work on string keys:

Psych.safe_load("---\n!ruby/object:DateTime 2024-01-17 11:19:12.359689000 +01:00: value\nkey: value\n", symbolize_names: true, permitted_classes: [Time, DateTime])
# => {#<DateTime: 2024-01-17T11:19:12+01:00 ((2460327j,37152s,359689000n),+3600s,2299161j)>=>"value", :key=>"value"}

@tenderlove
Copy link
Member

But just for the sake of the argument, symbolize_names does also only work on string keys:

Ya, you're right. Looking through commit history, it seems like that came from JSON.parse. I guess since we have documentation it's probably fine. I'll merge this. Thank you!

@tenderlove tenderlove merged commit be0ba74 into ruby:master Jan 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants