Base Conversion and Random Tokens: Because Sometimes You Need a Quick ID
Ruby can convert integers to any base from 2 to 36 with a single method call. Combined withrand or SecureRandom, you get instant token generation, temp file names, correlation IDs, and quick passwords. No gems, no dependencies. Just built-in Ruby being useful.
Part 1: Base Conversion with to_s(base)
Integer#to_s(base) converts to any base from 2 to 36 (digits 0-9 plus letters a-z).
Perl equivalent:# Convert to various bases 1234567890.to_s(2) # => "1001001100101100000001011010010" (binary) 1234567890.to_s(8) # => "11145401322" (octal) 1234567890.to_s(16) # => "499602d2" (hex) 1234567890.to_s(36) # => "kf12oi" (base 36)
sprintf handles hex/octal (%x, %o, %b), but no built-in for arbitrary bases. Ruby wins on flexibility here.
Part 2: Convert Back with to_i(base)
Round-trip conversion. Encode, decode, done."kf12oi".to_i(36) # => 1234567890 "499602d2".to_i(16) # => 1234567890 "1010".to_i(2) # => 10
Part 3: Quick and Dirty Random Tokens
Fast, no requires, good enough for temp files and log correlation. Not for security-sensitive tokens.rand(36**8).to_s(36) # 8-char random alphanumeric: "fmhpjfao" rand(36**6).to_s(36) # 6-char random: "bvhl8d"
Part 4: Secure Random Tokens
Userequire 'securerandom' SecureRandom.hex(8) # 16 hex chars: "a3f2b8c91d4e7f20" SecureRandom.hex(4) # 8 hex chars: "f2a8c91d" SecureRandom.alphanumeric(8) # 8 alphanumeric: "kT9mB2xL" SecureRandom.uuid # UUID: "550e8400-e29b-41d4-a716-446655440000" SecureRandom.base64(6) # base64: "cG5LmQ0N"
SecureRandom for anything security-related: session tokens, passwords, API keys.
Part 5: Ops Use Cases
These one-liners replace entire utility scripts. Need a random filename? One expression. Need a correlation ID? One expression. Need a password? One expression.# Generate temp file names tmpfile = "/tmp/backup_#{rand(36**6).to_s(36)}.tar.gz" # Generate log correlation IDs request_id = SecureRandom.hex(8) # Short session tokens token = SecureRandom.alphanumeric(12) # Quick password generation password = SecureRandom.alphanumeric(16)
Part 6: Dynamic Default Arguments Bonus
Related trick: Ruby evaluates default arguments at call time (not definition time):Perl equivalent: you'd handle this manually inside the sub withdef log_message(message, timestamp = Time.now) puts "[#{timestamp}] #{message}" end log_message("First") # uses current time sleep(2) log_message("Second") # uses NEW current time, 2 seconds later
$timestamp //= time(). Ruby does it automatically in the method signature. Cleaner, less boilerplate.
Created By: Wildcard Wizard. Copyright 2026