Saturday, May 4, 2013

Ruby Pig Latin

Often, the best way to learn a new language is to start off with small, simple programs. Sure, these programs won't be very useful, but they'll be fun to write and will help build your foundation in the language. Before you know it, you'll be writing more and more complex programs in the language.

I'm relatively new to Ruby. In order to learn more about Ruby String and Array methods, I wrote a program that prompts the user for a phrase, and spits out the phrase converted to Pig Latin.

There are several variants of Pig Latin, but the standard rules are (taken from Wikipedia)

  1. For words that begin with consonant sounds, the initial consonant or consonant cluster is moved to the end of the word, and "ay" is added, as in the following examples:
    • happy --> appyhay
    • duck --> uckday
    • glove" --> oveglay
  2. For words that begin with vowel sounds or silent letter, "e;way"e; is added at the end of the word. Examples are
    • egg --> eggway
    • inbox --> inboxway
    • eight --> eightway

My program is simplistic in that it can only discern consonants, and not consonant sounds. Regardless, it was still fun to write.

piglatin.rb


!/usr/bin/env ruby

def is_consonant?(c)
  letters = ('a'..'z').to_a
  consonants = letters - ['a', 'e', 'i', 'o', 'u']
  consonants.include? c
end

def starts_with_consonant?(s)
  c = s.slice(0,1).downcase
  is_consonant?(c)
end

def get_suffix(s)
  starts_with_consonant?(s) ? 'ay' : 'way'
end

def rotate_initial_consonants!(s)
  i = 0 
  while starts_with_consonant?(s) and i < s.length
    c = s.slice!(0,1)
    s << c
    i += 1
  end 
end

def to_piglatin(word)
  piglatin = String.new(word) 
  rotate_initial_consonants!(piglatin)
  piglatin << get_suffix(word) 
end

def get_words
  input = gets.chomp
  words = input.split
end

def main
  words = get_words
  output = []
  words.each do |word|
    output << to_piglatin(word)
  end 
  puts output.join(' ')
end

main

example


$ ./piglatin.rb
Storm the castle at dusk
ormStay ethay astlecay atway uskday

No comments:

Post a Comment