I was reading Why’s poignant guide to ruby and came upon this module on chapter 5:
require 'endertromb'
module WishScanner
def scan_for_a_wish
wish = self.read.detect do |thought|
thought.index( 'wish: ' ) == 0
end
wish.gsub( 'wish: ', '' )
end
end
I have been trying to figure out how it works but what is confusing me is how thought.index( 'wish: ' ) == 0 and wish.gsub( 'wish: ', '' ) work. According to the author the purpose of this method is to “only pick up a wish if it starts with the word wish and a colon and a space. That way the planet doesn’t fill up with every less-than-ten-letter word that appears in people’s heads.”
But the way I understand it, thought.index( 'wish: ' ) == 0 will check if thought starts with 'wish: '. However i dont understand wish.gsub( 'wish: ', '' ) in the way I see it it seems to just substitute wish with an empty string.
Can any one offer any explanation or further insight into it?
Thank you in advance for any help.
Exactly! It replaces the string
"wish: "in a string like"wish: A pony!"with"".I.e. it turns “wish: A pony!” into “A pony!”.