前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Ruby练习一=> {'a' => 3, 'man' => 1, 'canal' => 1, 'panama' => 1, 'plan' => 1}returns the list ["Pam", "

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

作者头像
用户2183996
发布2018-06-28 11:18:44
4010
发布2018-06-28 11:18:44
举报
文章被收录于专栏:技术沉淀

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)

代码语言:javascript
复制
> ```ruby
def palindrome?(string)
 # your code here
end
Example Code
代码语言:javascript
复制
#!/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}

代码语言:javascript
复制
> ```ruby
def count_words(string)
 # your code here
end
Example Code
代码语言:javascript
复制
#!/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

代码语言:javascript
复制
> 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
代码语言:javascript
复制
#!/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
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016.06.26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Why Homework?
    • Q1: Palindrome?
      • Q2: Count Words
      • => {'a' => 3, 'man' => 1, 'canal' => 1, 'panama' => 1, 'plan' => 1}
        • Q3: Rock Paper Scissors
        • returns the list ["Pam", "S"] wins since S>P
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档