Split - Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Split

We can build an array from our string by using .split. We can target where we want each element to be split at by specifying with our parameter. Using this quote by John Wayne, we'll split each word apart using spaces as our parameter.

j_str = "All I'm for is the liberty of the individual."

j_ary = j_str.split(" ") #Space between quotes.

print j_ary

["All", "I'm", "for", "is", "the", "liberty", "of", "the", "individual."]

Iterators

Iterators are Ruby methods you can use on collections and groups (i.e. Arrays and Hashes. We will talk about Hashes later.)

To iterate means to go over, traverse, or pass through. With the each method you can probably guess we're going to do something with each item in our collection.

our_numbers = [1, 2, 3, 4]

our_numbers.each do |num|

puts num * 2

end

2

4

6

8

When we called the each method we asked that it "do" something. We made each item in our array take the name of num during each iteration. What we put between the double pipes | | can be thought of as a temporary variable name. What you name the variable is up to you. It's best to use names that make sense of what you're doing. Ruby takes the first item in the list and executes all the way until it gets to end. Then it goes back to the array and grabs the second item and goes through. Why? Because we told it to do this for "each" item. You can see this better illustrated by adding a few puts:

our_numbers = [1, 2, 3, 4]

our_numbers.each do |num|

puts num * 2

puts num + 10

puts "next item in array"

end
puts "We're out!"

2

11

next item in array

4

12

next item in array

6

13

next item in array

8

14

next item in array

We're out!