[KATA ruby 練習-4 ]

Printer Errors

In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for the sake of simplicity, are named with letters from a to m.

The colors used by the printer are recorded in a control string. For example a “good” control string would be aaabbbbhaijjjm meaning that the printer used three times color a, four times color b, one time color h then one time color a...

Sometimes there are problems: lack of colors, technical malfunction and a “bad” control string is produced e.g. aaaxbbbbyyhwawiwjjjwwm.

You have to write a function printer_error which given a string will output the error rate of the printer as a string representing a rational whose numerator is the number of errors and the denominator the length of the control string. Don't reduce this fraction to a simpler expression.

The string has a length greater or equal to one and contains only letters from ato z.

#Examples:
s="aaabbbbhaijjjm"
error_printer(s) => "0/14"

s="aaaxbbbbyyhwawiwjjjwwm"
error_printer(s) => "8/22"

我的解法:

題目說顏色的字母表示是 a到 m,超過 m的就是 error。

最後要呈現的是 錯誤數量/ s的長度

要檢查 s裡是不是有超過 m的英文字,並且要算出數量。

第一個想到的就是 array.reject{|item|...}他的作用是可以判斷array裡的item ,如果 block的執行結果為 true,則從 array中刪除 item。 這樣我就可以刪掉 s 中是 a-m的字母。

然後在 ruby裡 要怎麼把 String變成 Array ? 可以使用 string.chars

Returns an array of characters in str. This is a shorthand for str.each_char.to_a.
def printer_error(s)     
  s_array = s.chars

colors = ['a', 'b', 'c', 'd', 'e' ,'f' ,'g' ,'h' ,'i' ,'j' ,'k' ,'l' ,'m']
  total_count = s_array.count

bad_colors_count = s_array.reject{|x| colors.include?(x)}.count

return new_s = "#{bad_colors_count}/#{total_count}"

end

解法二

其實最後可以直接用 String 解這題

def printer_error(s)   
"#{s.count('n-z')}/#{s.size}"
end

因為其實最後要的就是

s裡 n-z 出現的次數 / s的總字母數

Ruby 的字串有一個 count 方法,可簡單的算出字串中某些字母出現的次數

words = "Lorem Ipsum Dolor Sit Amet, Consectetur Adipiscing Elit." 
puts words.count("i")         # => 算出有幾個 i,共有 5 個 
puts words.count("A-Z") # => 算出所有大寫字母,共有 8 個
puts words.count("a-z") # => 算出所有小寫字母,共有 39 個