中关村村草 发表于 2012-02-25 11:08

RubyMonk系列题目(答案篇)

RubyMonk系列题目(答案篇)





#总算是有时间把之前在RubyMonk上搞的那些菜鸟题目做了一遍,也顺便温习巩固下基础知识。

一、数组篇
  1在下面的代码中,尝试提取超过五个字符的字符串。
        names = ['rock', 'paper', 'scissors', 'lizard', 'spock']



          names.each do |a|
            puts a if(a.length>5)
          end  2对于开发者而言,ruby之所以能这么流行的一个原因是它有着非常直观的API。很多时候,你都能在你脑海中猜到能完成你想要的目标的一些方法名称。尝试猜测一个你需要使用的方法来删除下面所给数组为“5”的元素。(注意是猜测哦,好吧,其实我早就知道了)
        .delete_if{|m| m==5}  3从下面给出的数组中删除所有给出的偶数
        .delete_if{|m| m%2==0}    原文:(Doing this in languages like C or Java would take you a lot of boiler plate code. The beauty of Ruby is in its concise but readable code.)
4给定一个包含有几个字符串的数组,编写一个length_finder方法,该方法接收一个数组为参数并够返回一个新数组,该新数组为对应数组参数的每个字符串元素的长度。(别吐槽我的水平了,我知道这个翻译的那是怎么听怎么别扭,应该能明白大概意思吧)Example:Given ['Ruby','Rails','C42'] the method should return
              def length_finder(input_array)
                input_array.map do |e|
                  e.length
                end
              end  4给定一个包含有多个单词的句子,编写一个名为“find_frequency”的方法,该方法有两个参数“sentence”和“word”,这两个参数都是字符串对象。并返回某一单词在该句子中的出现频率。示例:传入 'Ruby is The best language in the World' 和 'the',则返回“ 2”
提示: Array#count (用法自个儿查去)        
              def find_frequency(sentence, word)
                sentence.downcase.split(" ").count(word.downcase)
              end
  二、字符串篇



  1创建一个名为'random_select'的方法,该方法有两个参数,一个是数组对象array,另一个是数字n。该方法将返回从给定数组中随机选取n个新的元素组成新的数组。例如:给定数组和2应该返回随机从这个数组中随机挑选的两个数字所组成的新数组。
PS: 两次调用该方法最好返回不同的结果。   
          def random_select(array, n)
            result = []
            n.times do
              result << array
            end
            result
          end  2创建一个名为'sort_string'的方法,该方法接收一个字符串对象,并对这个字符串中的单词按照长度的升序进行重排序。假设没有其他的标点符号而只有单个空格分隔该字符串。例如:给定"Sort words in a sentence", 将返回"a in Sort words sentence".
              def sort_string(string)
                string.split(" ").sort{|a,b| a.length<=>b.length}.join(' ')
              end三、迭代器篇
  1复制存储在数组变量source中值小于4的元素到数组变量destination
            def array_copy(destination)
              source =
              source.each do |a|
                destination.push(a) if a< 4
              end
              destination
            end  
四、正则篇
  1将下面给出字符串中的大写字母都改为数字“0”
            'RubyMonk Is Pretty Brilliant'.gsub(//,'0')五、构建一个计算器
  创建一个计算器类,能够在同一时间完成两个数字的加减法。(不太懂,原文:Create a class Calculator, which performs the addition and subtraction of two numbers at a time. The sample code explains the expected API.)
          class Calculator
            def add(num_1, num_2)
              num_1 + num_2
             end



            def subtract(num_1, num_2)
              num_1 - num_2
            end
          end

星期六的深夜68 发表于 2012-02-25 11:08

谢谢分享
页: [1]
查看完整版本: RubyMonk系列题目(答案篇)