Ruby Development Protocol

3 cyri_k 1 5/5/2025, 4:47:40 PM sashite.github.io ↗

Comments (1)

vidarh · 23h ago
Some of these are great, but others need more justification.

E.g. section 1 and 2 would lead to very un-idiomatic Ruby other than 1.5 and 2.4, and the "Explicit Internal State Changes" section effectively neutralises a number of the restrictions in 1 and 2 (E.g. "Object state mutation is prohibited" except a whole section allows for mutating collections within the object)

Taken as a whole, as an internal policy for someone, this is fine, but I would strongly recommend Ruby beginners who don't know idiomatic Ruby well stay well clear of this document, as you'll end up writing code that'll look very out of place in most Ruby projects.

E.g. less problematic, but still somewhat unnuanced as a last example:

> Use String(x), Array(x), Integer(x) instead of x.to_s, x.to_a, x.to_i, etc.

These two sets have entirely different semantics, and while I think it's a reasonable first approximation for a beginner, there are cases where you explicitly want the second, and the advice leaves out "try_convert()" which are also important.

* E.g. you use Integer("x") when passing something that can't convert to integer is an unrecoverable error. You get an exception. When an exception is what you want, use this.

* You use `Integer.try_convert("42x")` you're dealing with, for example, user-provided input where the input should be an integer or something that claims (by implementing #to_int, rather than just #to_i) that it can be reasonably converted to an Integer (this includes Float, but Integer(float_value) also works, so if you want to be sure something can be represented precisely as an Integer you have extra work), but you can't reasonably fail the whole thing if it is not (try_convert() returns `nil` if the object isn't an Integer, and doesn't implement #to_int in a way that returns an Integer)

* You can use "to_int" instead of Integer.try_convert or Integer(), but the caveat is you'll get a NoMethodError instead of ArgumentError if the argument isn't convertible, so it's better to avoid.

* You use "to_i" if and only if the value isn't important and you just want a best effort conversion or 0. The most idiomatic use of this in Ruby is when the possible values are `nil` or an Integer, where using `to_i` is a common shorthand for "Integer.try_convert(foo) || 0" (caveat: you really want to be sure that it's okay to return 0 if `foo` is an entirely different type)