iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 30
0
自我挑戰組

Codewars Ruby Challenge in 30 Days系列 第 30

Codewars Ruby Challenge - Day 30/30

學習

  1. 轉換十六進位的方法:要將一般的十進位數字轉換成十六進位可以用「to_s(16)」非常方便,例如 17.to_s(16),會回傳 "11"
  2. 用 Format 轉換十六進位:Best Practice 提供的方法是 "%.2X%.2X%.2X" % [r, g, b] 這樣的方式。因為後面接的是陣列三個值,如果只有一個值直接寫「"%.2X" % 255」那就會回傳「"FF"」。其中的「2」指的是顯示兩位數,如果結果是 "1" 會變為 "01"。大寫的「X」就是要把前面的值轉換成十六進位且輸出的值會是大寫,像是結果是 "1e" 因為是大寫最後會變成 "1E"
  3. 想同時做到「a = 0 if a ≤ 0」與「a = 255 if a ≥ 255」:想做到這件事需要寫非常多行程式碼,在 Best Practice 中提到「[[a,255].min,0].max」這個超酷的做法(也不知道怎麼解釋,但一看就懂覺得超強XD)

題目:

The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.
Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.
The following are examples of expected output values:
rgb(255, 255, 255) # returns FFFFFF
rgb(255, 255, 300) # returns FFFFFF
rgb(0,0,0) # returns 000000
rgb(148, 0, 211) # returns 9400D3
翻譯:把 rgb 的 10 進位轉換成 16 進位

def rgb(r, g, b)

end

答案需要過以下測試:

RSpec.describe "RGB To Hex Conversion" do
  it "Example cases" do
    expect(rgb(0, 0, 0)).to eq('000000')
    expect(rgb(0, 0, -20)).to eq('000000')
    expect(rgb(300,255,255)).to eq('FFFFFF')
    expect(rgb(173,255,47)).to eq('ADFF2F')
  end
end

我的答案

def rgb(r, g, b)
  result = ""
  arr = [r, g, b]

  first = arr.map do |a|
            a = 255 if a >= 255
            a = 0 if a <= 0
            a
          end

  first.each do |n|
          result += n.to_s(16).length == 1 ? "0" + n.to_s(16).upcase : n.to_s(16).upcase
        end

  result
end

思路:

  1. 發現完全想不到怎麼轉 16 進位,查到了 .to_s(16) 轉換的方法
  2. 先處理了數值「大於 255」與「小於 0」的情況,然後以為很簡單的只要把答案 + 起來就好
  3. 後面發現如果傳入的值像是「1」,16 進位後會還是「1」,但我們需要轉換成「01」兩個位數的呈現

Best Practice in Codewars

def rgb(r, g, b)
  "%.2X%.2X%.2X" % [r,g,b].map{|i| [[i,255].min,0].max}
end

完賽心得

30 天完賽啦(撒花)~~~

不知不覺每天刷一題就完成了,已經有點像吃飯一樣,有種養成平常習慣的感覺。刷題加上發文大概 1.5 小時,喜歡這種不多不少的時間,同時每天都很踏實的學到新東西的感覺。

大概是因為最多只刷到 Codewars 第五級,還沒遇到太關於演算法的題目,學到比較多是在 Ruby 語法的應用,常常會有「原來這個語法可以這樣用」的 OS,比較多學習到的是「看過的語法新用途」,「學習新的語法」也佔了不少。
以一開始給自己設定的目標「提升 Ruby 語法實作」蠻有幫助的,對於刷題期間幾乎每天都在開發專案的壓力下,透過鐵人賽刷題這樣小壓力的方式來提升能力,相當推薦給其他新手~

接下來要繼續刷題嗎?會繼續!但可能會以 Ruby、JS 交錯著刷,畢竟想走後端工程師,Coding 上 JS 根本少不了,也是未來趨勢。

明年鐵人賽再見:)


上一篇
Codewars Ruby Challenge - Day 29/30
系列文
Codewars Ruby Challenge in 30 Days30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言