Python to Ruby
Recorder: the Python adapter (functions are imported and called; top-level code runs).
Frameworks: Flask, FastAPI and Django routes are found by analyze.
Constructs
- Errors:
raise ValueError(...)->raise ArgumentError, "...";KeyError->KeyError;IndexError->IndexError;TypeError->TypeError; the app's own exception classes ->class Name < StandardErrorwith the same name. - None ->
nil;Optional[T]parameters default tonil.x or defaultbehaves the same only whenxis never0,"",[]or{}: Python treats those as false, Ruby does not. Usex.presence || defaultor explicit checks. - Truthiness:
if items:->if items.any?(orunless items.empty?);if s:->unless s.empty?;if n:->unless n.zero?. - Comprehensions ->
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(stable in both);sum->sum. - Strings:
len, slicing and indexes count code points like RubyString#length/[];s[a:b]->s[a...b];s[-1]works the same; f-strings -> interpolation;str.split()with no argument ->split(both collapse whitespace) butsplit(" ")differs: Python keeps empty strings, Ruby'ssplit(" ")is awk-style; usesplit(/ /, -1). - Dicts keep insertion order like Ruby hashes. String keys stay strings (
"name"), not symbols, when they reach JSON. - Classes: dataclasses ->
Struct/Data.defineor plain classes;@property-> reader methods;__eq__/__hash__->==/eql?/hash. - Django/Flask: views -> controller actions;
request.args->params;jsonify(x)->render json: x;abort(404)->head :not_found(or the original's error body); Django ORM -> ActiveRecord (filter->where,exclude->where.not,get->find_by!,select_related->includes).
Traps
- Rounding:
round(2.5) == 2(half to even). Ruby2.5.round == 3. Useround(half: :even).round(x, 2)also rounds half to even on the binary value:round(2.675, 2) == 2.67. - Division:
/always returns a float (7 / 2 == 3.5,4 / 2 == 2.0); Ruby7 / 2 == 3. Usefdivor/ 2.0.//floors:-7 // 2 == -4like Ruby's-7 / 2. - Modulo takes the divisor's sign in both languages (
-7 % 2 == 1): same. - Ints vs floats:
difftells2from2.0; a function that returnsx / 2returns floats even for evenx. - Big ints never overflow in either language: same.
str.isalpha/isdigitare Unicode-aware; Ruby/[[:alpha:]]/is too,/[a-z]/is not.- Regex: Python
\w,\dmatch Unicode letters and digits; Ruby's are ASCII-only. Use\p{Word}/\p{Nd}or[[:alnum:]_]when the original sees non-ASCII text.re.matchanchors at the start only (\Ain Ruby);re.fullmatch->\A...\z. - Sorting mixed types raises
TypeErrorin Python; Ruby raisesArgumentError. - Default mutable arguments (
def f(x=[])) share state across calls; port the bug only if a recorded case shows it. - Clock and random: pin them (pass the time in), or ask the user about wildcards.