Ruby Language Iteration Iterating over complex objects

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Arrays

You can iterate over nested arrays:

[[1, 2], [3, 4]].each { |(a, b)| p "a: #{ a }", "b: #{ b }" }

The following syntax is allowed too:

[[1, 2], [3, 4]].each { |a, b| "a: #{ a }", "b: #{ b }" }

Will produce:

"a: 1"
"b: 2"
"a: 3"
"b: 4"

Hashes

You can iterate over key-value pairs:

{a: 1, b: 2, c: 3}.each { |pair| p "pair: #{ pair }" }

Will produce:

"pair: [:a, 1]"
"pair: [:b, 2]"
"pair: [:c, 3]"

You can iterate over keys and values simultaneously:

{a: 1, b: 2, c: 3}.each { |(k, v)| p "k: #{ k }", "v: #{ k }" }

Will produce:

"k: a"
"v: a"
"k: b"
"v: b"
"k: c"
"v: c"


Got any Ruby Language Question?