Ruby bits


Outline
  1. 1. 目錄
  2. 2. 1. Unless 更直覺
    1. 2.1. 一行表達 if
  3. 3. 2. nil treated as false
  4. 4. 3. 給予初始值 - “OR”
  5. 5. 4. RETURN VALUES
  6. 6. 5. Symbol

目錄

  1. if、Unless
  2. nil
  3. 給予初始值
  4. RETURN VALUES
  5. symbol

1. Unless 更直覺

1
2
3
4
5
6
7
8
9
10
11
# bad
if ! tweets.empty?
puts "Timeline:"
puts tweets
end

# good
unless tweets.empty?
puts "Timeline:"
puts tweets
end

一行表達 if

1
puts pin_number == pin ? "Balance: $#{@balance}." : pin_error
1
2
3
4
5
if pin_number == pin
puts "Balance: $#{@balance}."
else
puts pin_error
end

2. nil treated as false

1
2
3
4
5
6
7
8
9
# bad
if attachment.file_path != nil
attachment.post
end
# good
if attachment.file_path
attachment.post
end

3. 給予初始值 - “OR”

1
tweets = timeline.tweets || []
1
2
3
result = nil || 1 # =>1
result = 1 || nil # =>1
result = 1 || 2 # =>1
1
2
3
result2 = nil || 1 # =>1
等價於
result2 ||= 1 # =>1

但是 if else 比較易讀

4. RETURN VALUES

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# bad
def list_url(user_name, list_name)
if list_name
url = "https://twitter.com/#{user_name}/#{list_name}"
else
url = "https://twitter.com/#{user_name}"
end
url
end
# good
def list_url(user_name, list_name)
if list_name
"https://twitter.com/#{user_name}/#{list_name}"
else
"https://twitter.com/#{user_name}"
end
end

5. Symbol

string 與 symbol 轉換

1
2
3
4
5
6
7
8
"a".to_sym
=> :a
"a".intern
=> :a
:a.to_s
=> "a"
1
2
:hello.is_a? Symbol
=> true