Ruby练习一=> {'a' => 3, 'man' => 1, 'canal' => 1, 'panama' => 1, 'plan' => 1}returns the list ["Pam", "

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)

> ```ruby
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}

> ```ruby
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:

> ```ruby
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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏ml

hdu 1829 A Bug's Life(分组并查集(偏移量))

A Bug's Life Time Limit: 15000/5000 MS (Java/Others)    Memory Limit: 32768/3276...

3348
来自专栏小樱的经验随笔

FZU 2167 大王叫我来巡山呐

Problem 2167 大王叫我来巡山呐 Accept: 931    Submit: 1405 Time Limit: 1000 mSec    Memo...

3469
来自专栏ml

HDUOJ----2487Ugly Windows

Ugly Windows Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768...

2819
来自专栏ml

hdu-----(1532)Drainage Ditches(最大流问题)

Drainage Ditches Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/3...

2719
来自专栏量化投资与机器学习

【前沿】为什么Python是金融产品开发的最佳选择?

How do you nd your way and stay a oat in ntech? This new technology took the w...

742
来自专栏程序员的酒和故事

为什么C++不会衰老

Thoughts about C++ in the modern world. 一些关于当代C++的思考。 ? Debates about the pre...

3368
来自专栏Python中文社区

Python中文社区开源项目计划:ImagePy

开源图像处理框架,插件式设计,可以快速集成任何基于或支持numpy的图像处理算法,经过简单配置,快速生成交互环境,可供非计算机专业人员使用,可以理解为是算法研发...

781
来自专栏开发与安全

《dive into python3》 笔记摘录

0、In Python 2, the / operator usually meant integer division, but you could make...

2150
来自专栏ml

hdu-----(1507)Uncle Tom's Inherited Land*(二分匹配)

Uncle Tom's Inherited Land* Time Limit: 2000/1000 MS (Java/Others)    Memory Lim...

2284
来自专栏ml

hduoj-----(1068)Girls and Boys(二分匹配)

Girls and Boys Time Limit: 20000/10000 MS (Java/Others)    Memory Limit: 65536/3...

2285

扫码关注云+社区