Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
23: Working with JSON and YAML in Ruby
I see this a lot when developers first start dealing with external data: they assume that because JSON and YAML look like Ruby Hashes, they are Ruby Hashes. Specifically, there is a common belief that if you serialize a custom Ruby object into JSON and then parse it back, you'll get your original object back, complete with its methods and class identity.
Let's look at why that's a dangerous assumption. Imagine you have a Player class with a method called level_up!. You save the player to a JSON file and load it back later.
require 'json'
class Player
attr_accessor :name, :xp
def initialize(name, xp)
@name = name
@xp = xp
end
def level_up!
@xp += 100
puts "#{@name} leveled up!"
end
end
hero = Player.new("Link", 500)
json_data = hero.to_json # Serializing to JSON
parsed_hero = JSON.parse(json_data)
puts parsed_hero.class # Output: String (or Hash, depending on the serializer)
# parsed_hero.level_up! # This would throw a NoMethodError
The Myth of the Automatic Object vs. The Reality of Generic Data
What happened here? JSON doesn't know what a Player class is. It only knows strings, numbers, booleans, arrays, and objects (which Ruby maps to Hashes). When you call JSON.parse, Ruby gives you a Hash containing the data, but the behavior—the methods you wrote in your class—is gone. You aren't holding a Player object; you're holding a bag of data that happens to have the same keys as your Player attributes.
To fix this, you have to manually "rehydrate" your object. I usually do this by adding a factory method to the class that takes a hash as an argument and returns a new instance.
class Player
# ... existing code ...
def self.from_json(json_string)
data = JSON.parse(json_string)
new(data["name"], data["xp"])
end
end
# Now this works:
hero = Player.from_json(json_data)
hero.level_up! # "Link leveled up!"
Streaming Data with the JSON Library
JSON is the gold standard for APIs because it's lightweight and every language on earth understands it. In Ruby, the json library is your primary tool. While JSON.parse is what you'll use 90% of the time, don't forget JSON.generate (or .to_json) for the opposite direction.
One pro tip: if you're parsing an API response and you prefer symbols over strings for keys, pass the symbolize_names: true option. It makes your code feel much more "Ruby-ish" and prevents you from accidentally mixing data["name"] and data[:name] in the same file.
raw_response = '{"status": "success", "count": 42}'
data = JSON.parse(raw_response, symbolize_names: true)
puts data[:status] # "success"
Managing Configs with YAML
If JSON is for machines, YAML is for humans. You've probably seen .yml files in Rails projects for database configurations. YAML is far more flexible—it supports multi-line strings and comments—but it's slower to parse than JSON. Because of this, I never use YAML for high-frequency data transfer; I only use it for configuration files.
Ruby's yaml library (which is actually a wrapper around the Psych engine) makes this easy. You'll mostly use YAML.load_file to read a config and YAML.dump to write one.
require 'yaml'
app_config = {
"settings" => {
"theme" => "dark",
"notifications" => true,
"api_endpoint" => "https://api.example.com"
}
}
# Writing to a file
File.write("config.yml", YAML.dump(app_config))
# Reading from a file
config = YAML.load_file("config.yml")
puts config["settings"]["theme"] # "dark"
Just a word of caution: be careful with YAML.load when dealing with untrusted user input. YAML can be used to instantiate arbitrary Ruby classes, which can lead to remote code execution vulnerabilities. Always use YAML.safe_load or YAML.load_file (which is safe in modern Ruby versions) when you aren't 100% sure where the file came from.
📋 Practical Task
Exercise: Building a Game Character Save-and-Load System
You are building a simple RPG character manager. Your goal is to create a system that loads default settings from a YAML file and saves the final character state to a JSON file.
Requirements:
- Create a file named
defaults.ymlwith the following content:base_stats: strength: 10 agility: 10 intelligence: 10 starting_gold: 50 - Write a Ruby script that:
- Loads the
defaults.ymlfile. - Creates a
Characterclass that takes a name and thebase_statsfrom the YAML file. - Adds a method to the
Characterclass calledmodify_stat(stat, amount)to increase or decrease a specific stat. - Instantiates a character, modifies at least two of their stats, and then serializes the entire character object (including their name and updated stats) into a file called
save_slot_1.json.
- Loads the
- Verify that the
save_slot_1.jsonfile contains the updated values, not the defaults.
There are no comments for now.