Ruby bits (method 篇)


Outline
  1. 1. 目錄 (method 篇)
  2. 2. 1. OPTIONAL ARGUMENTS (給予參數初始值)
  3. 3. 2. HASH ARGUMENTS(參數太長)
    1. 3.1. better
    2. 3.2. Keys are optional
    3. 3.3. Complete hash is optional
  4. 4. 3. “SPLAT” ARGUMENTS

目錄 (method 篇)

  1. OPTIONAL ARGUMENTS
  2. HASH ARGUMENTS
  3. “SPLAT” ARGUMENTS

1. OPTIONAL ARGUMENTS (給予參數初始值)

1
2
3
4
5
6
7
8
9
10
11
# bad
def tweet(message, lat, long)
...
end
tweet("Practicing Ruby-Fu!", nil, nil)
# good
deftweet(message,lat=nil long=nil)
...
end
tweet("Practicing Ruby-Fu!")

2. HASH ARGUMENTS(參數太長)

1
2
3
4
5
6
7
8
def tweet(message, options = {})
status = Status.new
status.lat = options[:lat]
status.long = options[:long]
status.body = message
status.reply_id = options[:reply_id]
status.post
end
1
2
3
4
5
tweet("Practicing Ruby-Fu!",
:lat => 28.55,
:long => -81.33,
:reply_id => 227946
)

better

1
2
3
4
5
tweet("Practicing Ruby-Fu!",
lat: 28.55,
long: -81.33,
reply_id: 227946
)

Keys are optional

1
2
3
tweet("Practicing Ruby-Fu!",
lat: 28.55,
)

Complete hash is optional

1
tweet("Practicing Ruby-Fu!")

3. “SPLAT” ARGUMENTS

1
2
3
4
5
6
def mention(status, *names)
tweet("#{names.join(' ')} #{status}")
end
mention('Your courses rocked!', 'eallam', 'greggpollack', 'jasonvanlue')
=> eallam greggpollack jasonvanlue Your courses rocked!