Programming

Ruby on Rails 中使用 UUID primary key

PostgreSQL

在 PostgreSQL 中有支援 UUID 為唯一 ID,所以在 PostgreSQL 使用 UUID 是相對簡單的。在
migration 裡面,我們要告訴 PostgreSQL 使用 UUID extension,這樣能夠讓 PostgreSQL
自動對每一個物件建立唯一的 UUID,而不是讓 Ruby On Rails 花費額外的時間來處理。

使用 PostgreSQL 前在 Gemfile 中加上以下這行。

1
2
# Gemfile
gem 'pg'

設定 adapter 為 postgresql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
default: &default
adapter: postgresql
encoding: unicode
host: localhost
port: 5432
pool: 5
username: akii
password: <%= ENV['PG_PASSWORD'] %>

development:
<<: *default
database: development

test:
<<: *default
database: test

production:
<<: *default
database: production
# pool: 5
# url: <%= ENV['DATABASE_URL'] %>

設定 postgresql 的密碼

1
export PG_PASSWORD=xxxxxx

閱讀全文

Ruby Mix-in Module include 的規則

繼承關係

Ruby 只能繼承唯一一個 parent 的單純繼承,但藉由 Mix-in 機制,可以在單純繼承的架構下,在多個類別之間共享一些工能。

1
2
3
4
5
class Book
include Comparable
end

Book.ancestors # => [Book, Comparable, Object, Kernel]

Comparable 雖然不是 parent,但是運作情形差不多

1
2
3
4
5
6
7
8
9
10
11
┌────────────┐                                    ┌────────────┐
│ Object │ │ Object │
└────────────┘ └────────────┘
↑ ↑
│ ┌────────────┐ ┌────────────┐
│←──────────│ Comparable │ │ Comparable │
│ └────────────┘ └────────────┘
│ ↑
┌────────────┐ ┌────────────┐
│ Book │ │ Book │
└────────────┘ └────────────┘

閱讀全文

Ruby 多重指派 Multiple assignment

多重指派 Multiple assignment

一口氣做不只一個指派的動作時

盡量用在有關係的變數上,互相沒有關係的多重指派,只會讓程式很難懂。

1
a, b, c = 1, 2, 3

回傳方法不只一個

定義 Ruby 的方法時,有時候會想要傳回不只一個物件。這時傳回值也可以使用多重指派的方式取得回傳值。

1
2
3
4
5
6
def location()
...
return x, y, z
end

a, b, c = location()

閱讀全文

Ruby 內建變數與內建常數

指令輸出 ``

可以直接使用 `` 符號,框住要行的指令,取得執行的結果,回傳形式為字串。範例為列出所有 .rb 結尾的檔案。

1
2
3
4
files = `ls`
files.split.each do |file|
print "#{file}\n" if file =~ /.rb$/i
end

閱讀全文

Ruby One-Liners

From Here

翻轉每一行

輸入資料:

1
2
3
4
$ cat foo
qwe
123
bar

翻轉每一行的字:

1
2
3
4
$ ruby -e 'File.open("foo").each_line { |l| puts l.chop.reverse }'
ewq
321
rab

閱讀全文

Ruby 命令列選項 command line

偵錯、運作確認

-c: 語法檢查

檢查現在執行的 Ruby 指令稿語法是否正確。並不會實際執行程式。

-d: 設定偵錯模式

讓偵錯用變數 $DEBUG 生效。指定 -d 時, $DEBUG 的値會為 true。所以可以在程式裡加上這樣的敘述︰

1
print some_var if $DEBUG

閱讀全文

Ruby on Rails Debug ByeBug 使用

使用

在程式碼中想要中斷的地方加入 byebug,程式執行到 byebug 這個位置則會停下來讓使用者 debug。而至於進入 Debug 頁面能幹麻,大致上跟 GDB Debug 差不多,一步一步的執行,然後檢查每一個參數的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
# 進入 byebug 頁面
[9, 18] in /Users/akiicat/someplace.rb
9: byebug
10:
11: @message.save!
12:
13:
=> 14: @path = conversation_path(@conversation)
15: end
16:
17: private
18:
(byebug) d @path

閱讀全文

C 輸入資料常見的處理方式

Integer Type

給定總數

第一行先給定接下來要輸入資料的個數

1
2
3
4
3
1 2
3 4
5 6
1
2
3
4
5
6
7
int n, a, b;
scanf("%d", &n);
while (n--) { // 需要第幾筆資料的話,也可以用 for 迴圈往上加
scanf("%d %d", &a, &b);

// ...
}

閱讀全文