I’d really feel like I was doing you a disservice if I didn’t show you at least a little more of what strings can do (in Ruby, at least). Plus, if I do, I can give you more interesting exercises. ☺ Mind you, I’m still not going to show you even half, but I’ve just got to show you a little more.
Remember back here when I said a lot of the string methods also work on arrays? Well, it goes both ways: some of the array methods you’ve learned also work on strings.
Perhaps the most important and versatile is the […] method. The first thing you can do with it is pass in a number and get the character at that position in the string:
da_man = 'Mr. T' |
big_T = da_man[4] |
puts big_T |
T |
And then you can do fun stuff like this:
puts "Hello. My name is Julian." |
puts "I'm extremely perceptive." |
puts "What's your name?" |
|
name = gets.chomp |
puts "Hi, #{name}." |
|
if name[0] == 'C' |
puts 'You have excellent taste in footwear.' |
puts 'I can just tell.' |
end |
<= | Hello. My name is Julian. |
I'm extremely perceptive. | |
What's your name? | |
=> | Chris |
<= | Hi, Chris. |
You have excellent taste in footwear. | |
I can just tell. |
This is just the beginning of our friend, the […] method. Instead of picking out only one character, we can pick out substrings in two ways. One way is to pass in two numbers: the first tells us where to start the substring, and the second tells us how long of a substring we are looking for.
The second way, though, is quite possibly too sexy for your car: just pass in a range.
And both of these ways have a little twist. If you pass in a negative index, it counts from the end of the string. Dude!
prof = 'We tore the universe a new space-hole, alright!' |
puts prof[12, 8] |
puts prof[12..19] # 8 characters total |
puts |
def is_avi? filename |
filename.downcase[-4..-1] == '.avi' |
end |
# Vicarious embarrassment. |
puts is_avi?('DANCEMONKEYBOY.AVI') |
# Hey, I wasn't even 2 at the time... |
puts is_avi?('toilet_paper_fiasco.jpg') |
universe |
universe |
|
true |
false |
18.191.44.94