Remember how we got input from the user to fill in an array and handled a possible exception with begin/rescue in Getting Input? You can write that kind of code much more succinctly. First, let’s rewrite that code with a few methods to give it more structure:
| puts "Enter the numbers one by one, and end with an empty line:" |
| input_array # => for example: [78, 56, 12] |
| |
| def input_array |
| arr = [] of Int8 |
| while number = gets |
| number = number.strip # removes leading or trailing whitespace |
| if number == "" || number == "stop" |
| break |
| end |
| add_to_array(arr, number) |
| end |
| arr |
| end |
| |
| def add_to_array(arr, number) |
| begin |
| arr << number.to_i8 |
| rescue |
| puts "integer bigger than 255" |
| end |
| end |
The method add_to_array now handles the possible exception. You can write this more concisely by leaving out the begin keyword, as shown here:
| def add_to_array(arr, number) |
| arr << number.to_i8 |
| rescue |
| puts "integer bigger than 255" |
| end |
This shorthand also works for ensure, which is usually used for freeing resources or cleaning up.
18.191.176.5