Skip to content

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 < StandardError with the same name.
  • None -> nil; Optional[T] parameters default to nil. x or default behaves the same only when x is never 0, "", [] or {}: Python treats those as false, Ruby does not. Use x.presence || default or explicit checks.
  • Truthiness: if items: -> if items.any? (or unless 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 Ruby String#length/[]; s[a:b] -> s[a...b]; s[-1] works the same; f-strings -> interpolation; str.split() with no argument -> split (both collapse whitespace) but split(" ") differs: Python keeps empty strings, Ruby's split(" ") is awk-style; use split(/ /, -1).
  • Dicts keep insertion order like Ruby hashes. String keys stay strings ("name"), not symbols, when they reach JSON.
  • Classes: dataclasses -> Struct / Data.define or 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). Ruby 2.5.round == 3. Use round(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); Ruby 7 / 2 == 3. Use fdiv or / 2.0. // floors: -7 // 2 == -4 like Ruby's -7 / 2.
  • Modulo takes the divisor's sign in both languages (-7 % 2 == 1): same.
  • Ints vs floats: diff tells 2 from 2.0; a function that returns x / 2 returns floats even for even x.
  • Big ints never overflow in either language: same.
  • str.isalpha/isdigit are Unicode-aware; Ruby /[[:alpha:]]/ is too, /[a-z]/ is not.
  • Regex: Python \w, \d match Unicode letters and digits; Ruby's are ASCII-only. Use \p{Word} / \p{Nd} or [[:alnum:]_] when the original sees non-ASCII text. re.match anchors at the start only (\A in Ruby); re.fullmatch -> \A...\z.
  • Sorting mixed types raises TypeError in Python; Ruby raises ArgumentError.
  • 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.
Edit this page on GitHub →