如果今天的答案一路 chain 下去
num.to_s.split("").map.with_index { |n, i| n + '0' * (num.to_s.length - i - 1)}.select { |n| n.to_i != 0 }.join(" + ")
說明:閱讀上超難看懂用了哪些方法
如果今天的答案用「多行鏈結」好的 coding style
num.to_s
.split("")
.map
.with_index { |n, i| n + '0' * (num.to_s.length - i - 1)}
.select { |n| n.to_i != 0 }
.join(" + ")
說明:上面提供的參考文章有提到「比起橫向閱讀,人更擅長縱向閱讀」,很明顯這樣的寫法很好看清楚程式流程、用了哪些方法
You will be given a number and you will need to return it as a string in Expanded Form. For example:
expanded_form(12); # Should return '10 + 2'
expanded_form(42); # Should return '40 + 2'
expanded_form(70304); # Should return '70000 + 300 + 4'
# 翻譯:把 input 的數字拆成各分位的相加 ex. 12 -> '10 + 2'
def expanded_form(num)
end
RSpec.describe "Write Number in Expanded Form" do
it "Example cases" do
expect(expanded_form(12)).to eq('10 + 2')
expect(expanded_form(42)).to eq('40 + 2')
expect(expanded_form(70304)).to eq('70000 + 300 + 4')
end
end
def expanded_form(num)
num.to_s
.split("")
.map
.with_index { |n, i| n + '0' * (num.to_s.length - i - 1)}
.select { |n| n.to_i != 0 }
.join(" + ")
end
def expanded_form(num)
num.to_s
.chars
.reverse
.map.with_index { |d, idx| d.to_i * 10**idx }
.reject(&:zero?)
.reverse
.join (' + ')
end