- Published
- Author
- Nived HariSystem Analyst
In Ruby, there are two ways to define hash keys:
1. Using the Colon Syntax (
Key Behavior: The key is treated as a fixed symbol (e.g.,
2. Using the Hash Rocket (
Key Behavior: The left-hand side is evaluated dynamically, making it useful for variable-based keys.
Example Use Case: Dynamic Keys
Here,
When to Use
• When working with multiple models that have different column names
• When dynamically generating hash keys at runtime
• When building flexible APIs that handle varying attribute names
Takeaway:
• Use
• Use
#ruby
1. Using the Colon Syntax (
:) – Creates a Literal Symbol KeyCode
item.update!(
ordered_quantity: new_quantity,
)Key Behavior: The key is treated as a fixed symbol (e.g.,
:ordered_quantity).2. Using the Hash Rocket (
=>) – Evaluates the Left-Hand Side as a KeyCode
item.update!(
quantity_field => new_quantity,
)Key Behavior: The left-hand side is evaluated dynamically, making it useful for variable-based keys.
Example Use Case: Dynamic Keys
Code
quantity_field = item.respond_to?(:ordered_quantity) ? :ordered_quantity : :quantity
new_quantity = item.public_send(quantity_field).to_i + item_case[:quantity].to_i
item.update!(
quantity_field => new_quantity, # Evaluates to :ordered_quantity or :quantity
)Here,
quantity_field is determined dynamically based on the model, so => must be used instead of :.When to Use
=>?• When working with multiple models that have different column names
• When dynamically generating hash keys at runtime
• When building flexible APIs that handle varying attribute names
Takeaway:
• Use
: when the key is static and always the same.• Use
=> when the key is stored in a variable or needs to be evaluated dynamically.#ruby