從 Python 到 Ruby
Recorder:Python adapter(函式會被 import 後呼叫;頂層程式碼會執行)。框架:Flask、FastAPI 與 Django 的路由會由 analyze 找出。
語法結構
- 錯誤:
raise ValueError(...)->raise ArgumentError, "...";KeyError->KeyError;IndexError->IndexError;TypeError->TypeError;應用程式自己的例外類別 -> 同名的class Name < StandardError。 - None ->
nil;Optional[T]參數預設為nil。只有在x永遠不會是0、""、[]或{}時,x or default的行為才會相同:Python 把這些視為 false,Ruby 則不會。請使用x.presence || default或明確的檢查。 - 真值判斷:
if items:->if items.any?(或unless items.empty?);if s:->unless s.empty?;if n:->unless n.zero?。 - Comprehension ->
map/select/filter_map/each_with_object;dict(zip(a, b))->a.zip(b).to_h;enumerate->each_with_index;sorted(x, key=f)->sort_by(兩者都是穩定排序);sum->sum。 - 字串:
len、切片與索引都以 code point 計算,和 Ruby 的String#length/[]一樣;s[a:b]->s[a...b];s[-1]的行為相同;f-string -> 字串插值;不帶參數的str.split()->split(兩者都會合併連續空白),但split(" ")不同:Python 會保留空字串,Ruby 的split(" ")則是 awk 風格;請使用split(/ /, -1)。 - Dict 和 Ruby hash 一樣保留插入順序。字串鍵在輸出成 JSON 時仍是字串(
"name"),而不是 symbol。 - 類別:dataclass ->
Struct/Data.define或一般類別;@property-> reader 方法;__eq__/__hash__->==/eql?/hash。 - Django/Flask:view -> controller action;
request.args->params;jsonify(x)->render json: x;abort(404)->head :not_found(或原版的錯誤 body);Django ORM -> ActiveRecord(filter->where,exclude->where.not,get->find_by!,select_related->includes)。
陷阱
- 四捨五入:
round(2.5) == 2(四捨六入五成雙)。Ruby 是2.5.round == 3。請使用round(half: :even)。round(x, 2)也會依二進位值以四捨六入五成雙處理:round(2.675, 2) == 2.67。 - 除法:
/一律回傳浮點數(7 / 2 == 3.5、4 / 2 == 2.0);Ruby 是7 / 2 == 3。請使用fdiv或/ 2.0。//是向下取整:-7 // 2 == -4,和 Ruby 的-7 / 2一樣。 - 取餘數在兩種語言中都跟隨除數的正負號(
-7 % 2 == 1):相同。 - 整數與浮點數:
diff能分辨2與2.0;回傳x / 2的函式,即使x是偶數也會回傳浮點數。 - 大整數在兩種語言中都不會溢位:相同。
str.isalpha/isdigit支援 Unicode;Ruby 的/[[:alpha:]]/也支援,但/[a-z]/不支援。- 正規表示式:Python 的
\w、\d會比對 Unicode 字母與數字;Ruby 的則只比對 ASCII。當原版會處理非 ASCII 文字時,請使用\p{Word}/\p{Nd}或[[:alnum:]_]。re.match只錨定開頭(Ruby 中的\A);re.fullmatch->\A...\z。 - 混合型別排序在 Python 中會拋出
TypeError;Ruby 則拋出ArgumentError。 - 可變的預設參數(
def f(x=[]))會在多次呼叫間共用狀態;只有在錄製案例顯示出這個 bug 時才移植它。 - 時鐘與亂數:把它們固定住(把時間當參數傳入),或詢問使用者是否使用萬用字元。