Chapter 5 - Arrays and Blocks
Exercise 1: Converting a String to an Array and back
This string is supposed to contain a list of fruit, separated by commas. But there are some items in there that shouldn’t be:
Write a script that does the following:
- Use the
split
method with an argument of", "
to split the string into an array. - Use the
pop
method to discard the last array element. - Use the
shift
method to discard the first array element. - Use the
join
method with an argument of", "
to join the array back into a string, and print the result.
You should get the following output:
When you’re ready, have a look at the solution.
Exercise 2: Yielding to a block
Write a method named with_these_numbers
so that the following code will work:
Some hints:
- Your method will need to accept two parameters.
- Your finished method body will probably be a single line of code.
- You’ll need to use the
yield
keyword within the method body, to yield to the block. - You’ll need to pass the two method parameters as arguments to
yield
, so that they’re passed on to the block.
When you’re ready, have a look at the solution.
Exercise 3: IRB session
Launch irb
from your terminal, and try the following expressions:
After you try them out, you can see an explanation of the results.