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 条评论
登录 后参与评论

相关文章

来自专栏算法修养

FZU 2098 刻苦的小芳(卡特兰数,动态规划)

Problem 2098 刻苦的小芳 Accept: 42 Submit: 70 Time Limit: 1000 mSec Memory ...

3106
来自专栏码匠的流水账

聊聊storm supervisor的启动

storm-core-1.2.2-sources.jar!/org/apache/storm/daemon/supervisor/Supervisor.java

1093
来自专栏函数式编程语言及工具

PICE(2):JDBCStreaming - gRPC-JDBC Service

   在一个akka-cluster环境里,从数据调用的角度上,JDBC数据库与集群中其它节点是脱离的。这是因为JDBC数据库不是分布式的,不具备节点位置透明化...

800
来自专栏函数式编程语言及工具

Akka(17): Stream:数据流基础组件-Source,Flow,Sink简介

    在大数据程序流行的今天,许多程序都面临着共同的难题:程序输入数据趋于无限大,抵达时间又不确定。一般的解决方法是采用回调函数(callback-funct...

2736
来自专栏码匠的流水账

reactor-netty中HttpClient对TcpClient的封装

本文主要研究一下reactor-netty中HttpClient对TcpClien的封装

1801
来自专栏Clive的技术分享

代码重构的方法

1674
来自专栏叁金大数据

C#调用C++ Dll

现在项目基本都是旁边C++的哥们做好dll扔给我,然后我调用。好久之前晚上down了一份c#调用c++dll的方法,出处早已经遗忘。闲来无事,放上来好了。原作者...

1352
来自专栏码匠的流水账

聊聊storm的LoggingMetricsConsumer

storm-2.0.0/storm-client/src/jvm/org/apache/storm/metric/LoggingMetricsConsumer....

993
来自专栏数据结构与算法

BZOJ2434: [Noi2011]阿狸的打字机(AC自动机 树状数组)

1043
来自专栏移动端开发

iOS RunTime你知道了总得用一下

说点题外话: 我刚来现在这家公司的时候,老板让我下载一个脉脉,上去找找自己的同行,多认识些同行。其实初衷的好的,但最近这两天我把它卸载了,不为别的,负能量太多...

2029

扫码关注云+社区