嗨,我是 Fly,用 Ruby 寫 Chatbot 並挑戰30天分享心得
為確保不會沒靈感
每日含 Ruby 主題文章增加內容
https://github.com/leo424y/clean-code-ruby
一個變數指一件事,函數作用後是另件事了
Bad:
# Global variable referenced by following function.
# If we had another function that used this name, now it'd be an array and it could break it.
$name = 'Ryan McDermott'
def split_into_first_and_last_name
$name = $name.split(' ')
end
split_into_first_and_last_name()
puts $name # ['Ryan', 'McDermott']
Good:
def split_into_first_and_last_name(name)
name.split(' ')
end
name = 'Ryan McDermott'
new_name = split_into_first_and_last_name(name)
puts name # 'Ryan McDermott'
puts new_name # ['Ryan', 'McDermott']
再次避免搞混變數及函式
Bad:
def add_item_to_cart(cart, item)
cart.push(item: item, time: Time.now)
end
Good:
def add_item_to_cart(cart, item)
cart + [{ item: item, time: Time.now }]
end