Ruby - Module File Inclusion

Introduction

Let's write an extension to the String class:

Consider this code:

Demo

class String 
  def vowels # from  ww  w  . j a  v a  2s  .  c  om
    self.scan(/[aeiou]/i) 
  end 
end 


puts "This is a test".vowels.join('-')

Result

Here, you've extended String with a vowels method.

The vowels method uses scan to return an array of all the vowels.

The i option on the end makes the regular expression case-insensitive.

We can put this code in a file called string_extensions.rb:

class String 
 def vowels 
   self.scan(/[aeiou]/i) 
 end 
end 

And put this code in a file called vowel_test.rb:

require 'string_extensions' 
puts "This is a test".vowels.join('-') 

The first line, require 'string_extensions', loads in the string_extensions.rb file and processes it as if the code were local.

Related Topics