Why Homework?
These problems are excellent for ruby learning and is homework for some course, like CSCE606 at Texas A&M University.
And one good way to get quick start with a language is:
- Read documents quickly to get familiar with basic grammar
- Then code, code and code
If you can find a good problem series, then life will become easier. Here I post some ruby homework which I think is pretty beneficial for you study on ruby and rails.
So let’s go and write some code.
It maybe hard at first. But don’t give up, just go to Google and Stack Overflow
Q1: Palindrome?
Write a method that determines whether a given word or phrase is a palindrome, that is, it reads the same backwards as forwards, ignoring case, punctuation, and nonword characters. (characters that Ruby regexps would treat as nonword characters, that is, as boundaries between words). Your solution should not use any iteration. The rubular.com may be helpful in developing appropriate Ruby regular expressions. Methods you might find useful include: String#downcase, String#gsub and String#reverse. Suggestion: Use method chaining to make your code look more beautiful. Examples:
palindrome?("A man, a plan, a canal -- Panama") #=> true
palindrome?("Madam, I'm Adam!") # => true
palindrome?("Abracadabra") # => false (nil is also ok)
def palindrome?(string)
# your code here
end
Example Code
#!/usr/bin/env ruby
# encoding: utf-8
#Run this program and enter the word or phrase you
#wanna test, you will see the result!
def palindrome?
print "Enter here: "
text = gets.chomp.downcase.gsub(/[\W|_]/,"")
if text == text.reverse
puts "Palindrome? #{true}"
else
puts "Palindrome? #{false}"
end
end
Q2: Count Words
Given a string of input, return a hash whose keys are words in the string and whose values are the number of times each word appears. Do not use for-loops. Iterators such as each are permitted. Nonwords should be ignored. Case should not matter. A word is defined as a string of characters between word boundaries. (“\b” in a Ruby regexp means matches word boundaries). Example:
count_words("A man, a plan, a canal -- Panama")
# => {'a' => 3, 'man' => 1, 'canal' => 1, 'panama' => 1, 'plan' => 1}
count_words "Doo bee doo bee doo" # => {'doo' => 3, 'bee' => 2}
def count_words(string)
# your code here
end
Example Code
#!/usr/bin/env ruby
# encoding: utf-8
# Used to count the times each word appear in a string
def count_words
print "Enter your string: "
words = gets.chomp.scan(/\b[a-z]+/)
# or use this
# string = gets.chomp.downcase.gsub(/\W*$/,"")
# words = string.split(/\b\W+\b/) # put each word in an Array
dict = Hash.new
words.each do |word|
if dict.has_key?(word)
dict[word] += 1
else
dict[word] = 1
end
end
return dict
end
Q3: Rock Paper Scissors
In a game of rock-paper-scissors, each player chooses to play Rock (R), Paper (P), or Scissors (S). The rules are: Rock beats Scissors (R>S), Scissors beats Paper (S>P), but Paper beats Rock (P>R). A rock-paper-scissors game is encoded as a list, where each list element is a two-element list that encodes a player’s name and a player’s strategy.
[ [ "Kristen", "P" ], [ "Pam", "S" ] ]
# returns the list ["Pam", "S"] wins since S>P
Write a method rps_game_winner that takes a two-element list and behaves as follows:
- If the number of players is not equal to 2, raise WrongNumberOfPlayersError.
- If either player’s strategy is something other than “R”, “P” or “S” (case-insensitive), raise NoSuchStrategyError.
- Otherwise, return the name and strategy of the winning player. If both players use the same strategy, the first player is the winner.
Here is some code scaffolding:
class WrongNumberOfPlayersError < StandardError
end
class NoSuchStrategyError < StandardError
end
def rps_game_winner(game)
raise WrongNumberOfPlayersError unless game.length == 2
# your code here
end
Example Code
#!/usr/bin/env ruby
# encoding: utf-8
class WrongNumberOfPlayersError < StandardError ;end
class NoSuchStrategyError < StandardError ;end
def rps_game_winner(list)
# check num of players
raise WrongNumberOfPlayersError unless list.length == 2
# check strategy
list.each do |temp|
raise NoSuchStrategyError unless ['r','p','s'].include?(temp[1].downcase)
end
strategy_1 = list[0][1].downcase
strategy_2 = list[1][1].downcase
case [strategy_1,strategy_2]
when ['r','p'],['p','s'],['s','r'] #the latter one wins
flag = 1
else
flag = 0 # include tie, the former one wins
end
return list[flag]
end
if __FILE__ == $0
#list = [["Kristen","R"],["Pam","S"]] # enter strategies here
#list = [["Kristen","R"],["Pam","S"],["Kaihatu",'P']]
list = [["Kristen","R"], ["Pam","S"]]
print rps_game_winner(list)
end