- 論壇徽章:
- 0
|
RubyMonk系列題目(答案篇)
#總算是有時(shí)間把之前在RubyMonk上搞的那些菜鳥題目做了一遍,也順便溫習(xí)鞏固下基礎(chǔ)知識。
一、數(shù)組篇
1在下面的代碼中,嘗試提取超過五個(gè)字符的字符串。- names = ['rock', 'paper', 'scissors', 'lizard', 'spock']
-
- names.each do |a|
- puts a if(a.length>5)
- end
復(fù)制代碼 2對于開發(fā)者而言,ruby之所以能這么流行的一個(gè)原因是它有著非常直觀的API。很多時(shí)候,你都能在你腦海中猜到能完成你想要的目標(biāo)的一些方法名稱。嘗試猜測一個(gè)你需要使用的方法來刪除下面所給數(shù)組為“5”的元素。(注意是猜測哦,好吧,其實(shí)我早就知道了)- [1,3,5,4,6,7].delete_if{|m| m==5}
復(fù)制代碼 3從下面給出的數(shù)組中刪除所有給出的偶數(shù)- [1,2,3,4,5,6,7,8,9].delete_if{|m| m%2==0}
復(fù)制代碼 原文:(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給定一個(gè)包含有幾個(gè)字符串的數(shù)組,編寫一個(gè)length_finder方法,該方法接收一個(gè)數(shù)組為參數(shù)并夠返回一個(gè)新數(shù)組,該新數(shù)組為對應(yīng)數(shù)組參數(shù)的每個(gè)字符串元素的長度。(別吐槽我的水平了,我知道這個(gè)翻譯的那是怎么聽怎么別扭,應(yīng)該能明白大概意思吧)Example:- Given ['Ruby','Rails','C42'] the method should return [4,5,3]
- def length_finder(input_array)
- input_array.map do |e|
- e.length
- end
- end
復(fù)制代碼 4給定一個(gè)包含有多個(gè)單詞的句子,編寫一個(gè)名為“find_frequency”的方法,該方法有兩個(gè)參數(shù)“sentence”和“word”,這兩個(gè)參數(shù)都是字符串對象。并返回某一單詞在該句子中的出現(xiàn)頻率。示例:傳入 'Ruby is The best language in the World' 和 'the',則返回“ 2”
提示: Array#count (用法自個(gè)兒查去)- def find_frequency(sentence, word)
- sentence.downcase.split(" ").count(word.downcase)
- end
復(fù)制代碼 二、字符串篇
1創(chuàng)建一個(gè)名為'random_select'的方法,該方法有兩個(gè)參數(shù),一個(gè)是數(shù)組對象array,另一個(gè)是數(shù)字n。該方法將返回從給定數(shù)組中隨機(jī)選取n個(gè)新的元素組成新的數(shù)組。例如:給定數(shù)組[1,2,3,4,5]和2應(yīng)該返回隨機(jī)從這個(gè)數(shù)組中隨機(jī)挑選的兩個(gè)數(shù)字所組成的新數(shù)組。
PS: 兩次調(diào)用該方法最好返回不同的結(jié)果。- def random_select(array, n)
- result = []
- n.times do
- result << array[rand(array.length)]
- end
- result
- end
復(fù)制代碼 2創(chuàng)建一個(gè)名為'sort_string'的方法,該方法接收一個(gè)字符串對象,并對這個(gè)字符串中的單詞按照長度的升序進(jìn)行重排序。假設(shè)沒有其他的標(biāo)點(diǎn)符號而只有單個(gè)空格分隔該字符串。例如:給定"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
復(fù)制代碼 三、迭代器篇
1復(fù)制存儲(chǔ)在數(shù)組變量source中值小于4的元素到數(shù)組變量destination- def array_copy(destination)
- source = [1, 2, 3, 4, 5]
- source.each do |a|
- destination.push(a) if a< 4
- end
- destination
- end
復(fù)制代碼 四、正則篇
1將下面給出字符串中的大寫字母都改為數(shù)字“0”- 'RubyMonk Is Pretty Brilliant'.gsub(/[A-Z]/,'0')
復(fù)制代碼 五、構(gòu)建一個(gè)計(jì)算器
創(chuàng)建一個(gè)計(jì)算器類,能夠在同一時(shí)間完成兩個(gè)數(shù)字的加減法。(不太懂,原文: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
復(fù)制代碼 |
|