Concept Flow - Accessing and setting values
Start
Access value by key/index
Use value or modify it
Set new value by key/index
Check updated value
End
This flow shows how to get a value from a data structure and then change it by setting a new value.
hash = {a: 1, b: 2}
puts hash[:a]
hash[:a] = 10
puts hash[:a]| Step | Action | Expression | Result | Output |
|---|---|---|---|---|
| 1 | Create hash | hash = {a: 1, b: 2} | {:a=>1, :b=>2} | |
| 2 | Access value by key :a | hash[:a] | 1 | 1 |
| 3 | Set new value for key :a | hash[:a] = 10 | 10 | |
| 4 | Access updated value by key :a | hash[:a] | 10 | 10 |
| Variable | Start | After Step 1 | After Step 3 | Final |
|---|---|---|---|---|
| hash | nil | {:a=>1, :b=>2} | {:a=>10, :b=>2} | {:a=>10, :b=>2} |
Accessing and setting values in Ruby: - Use hash[key] to get a value. - Use hash[key] = value to set or update. - Access returns current value. - Setting changes the stored value. - Works similarly for arrays with indexes.