CSCI305.github.io

CSCI 305 Programming Languages

Ruby Part 1

Reading: Ruby Tutorial Sections 3, 5, 6, 7, 13, 14, and 15

Installing Ruby: You can install ruby using instructions found at the following sites:

Outside of Class

Watch this Video - (1:35:29)

OR

Watch these videos (the above video broken into 6 parts for easier consumption):

Explore Ruby:

Outline:

In class exercises Solutions Video (10:24):

Excercise 1:

Write a ruby program which prompts for and reads one line of input. It then echos the line, then prints it repeatedly, each time removing every second character. It continues until no more characters can be removed. Treat all characters alike; no special treatment for spaces or punctuation

isaac@sparqline001 $ ruby reduce.rb
Please enter a line> Sandy.
Sandy.
Sny
Sy
S
isaac@sparqline001 $ ruby reduce.rb
Please enter a line> On Tuesday, Frank in the motor pool buys lunch.
On Tuesday, Frank in the motor pool buys lunch.
O usa,Faki h oo olby uc.
OuaFk  oob c
Oak o
Oko
Oo
O
isaac@sparqline001 $ ruby reduce.rb
Please enter a line> Those so aglow point at hues afferent
Those so aglow point at hues afferent
Toes go on the feet
Te oo h et
T ohe
Toe
Te
T

Solution:

print "Please enter a line> "
line = gets.chomp

puts line

until line.length < 2
  new_line = ""
  (0..(line.length - 1)).step(2) do |i|
    new_line += line[i]
  end

  puts new_line
  line = new_line
end

Exercise 2 (A Solution):

Write a quick ruby script to determine if a word is a palindrome. This script should prompt the user for a single line of input and then echo the input, its reverse, and then whether or not it is a palindrome (regardless of case).

isaac@sparqline001 $ ruby palindrome.rb
Please enter a word> Bob
Bob
boB
Bob is a palindrome

Modification (A Solution)

Modify Exercise 2 such that if given a string with multiple words that forms a single palindrome when spaces are removed, you can detect that as well. Echo out the space reduced form of the line, its reverse, and whether or not it is a palindrome.

isaac@sparqline001 $ ruby palindrome2.rb
Please enter a line> Was it a car or a cat i saw
Was it a car or a cat i saw
was i tac a ro rac a ti saW
Wasitacaroracatisaw
wasitacaroracatisaW
The line is a palindrome

Solution:

def palindrome? str
  str == str.reverse
end

print "Enter a line> "
line = gets.chomp

puts line
puts line.reverse

line.gsub!(/\s/, '')
puts line
puts line.reverse

puts "#{line} is a palindrome" if palindrome? line.downcase