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

相关文章

来自专栏数说工作室

统计师的Python日记【第4天:欢迎光临Pandas】

本文是【统计师的Python日记】第4天的日记 回顾一下: 第1天学习了Python的基本页面、操作,以及几种主要的容器类型; 第2天学习了python的函数、...

3889
来自专栏码匠的流水账

聊聊storm supervisor的启动

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

1463
来自专栏程序员宝库

Java 8 时间 API 快速入门

Java 8 出来很久了,各位也可能已经在用了,不过其中新的时间日期 API 可能很少人用,甚至不知道怎么上手。本文快速介绍一下其中的主要的类的概念和用法。 一...

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

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

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

2946
来自专栏移动端开发

iOS RunTime你知道了总得用一下

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

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

Akka(23): Stream:自定义流构件功能-Custom defined stream processing stages

    从总体上看:akka-stream是由数据源头Source,流通节点Flow和数据流终点Sink三个框架性的流构件(stream components)...

4248
来自专栏FD的专栏

编辑器背后的数据结构

大约刚上大二的时候,想做一个编辑器控件。不是一个用Scintilla套上外壳的编辑器,而是一个能被套上外壳的控件。当然它最后也成为了我众多流产了的练手项目中的一...

1293
来自专栏码匠的流水账

聊聊jump consistent hash

jump consistent hash是一致性哈希的一种实现,论文见A Fast, Minimal Memory, Consistent Hash Algor...

1892
来自专栏码匠的流水账

聊聊storm的JoinBolt

storm-2.0.0/storm-client/src/jvm/org/apache/storm/bolt/JoinBolt.java

1524
来自专栏算法修养

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

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

3156

扫码关注云+社区