Ruby Cheat Sheet
Basics
puts "Hi #{name}"; print "x"; p obj
name = gets.chomp; n = gets.to_i
x ||= 5; y = cond ? a : b; obj&.method
"42".to_i; 3.to_s; "3.5".to_f; :sym.to_s; "s".to_sym
Control flow
if a then b elsif c then d else e end
puts "ok" if valid; puts "no" unless valid
case x when 1..5 then "low" when String then "str" else "other" end
5.times { |i| }; 1.upto(10) { |i| }; arr.each_with_index { |v, i| }
Arrays and hashes
a = [3, 1, 2]; a << 4; a.push(5); a.pop; a.sort; a.uniq; a.flatten; a.compact
a.map { |x| x * 2 }; a.select(&:even?); a.reject(&:nil?); a.reduce(:+); a.sum; a.tally
h = { name: "Asha" }; h[:age] = 20; h.fetch(:x, 0); h.each { |k, v| }; h.keys; h.to_a
a.group_by { |x| x % 2 }; a.sort_by { |x| -x }; a.each_slice(2).to_a
Methods and classes
def add(a, b = 0, *rest, key: 1, &blk) = a + b
class User < Base; attr_accessor :name; def initialize(name) = @name = name; end
module Loggable; def log(msg) = puts(msg); end
User.new("Asha"); obj.respond_to?(:name)
Errors and files
begin; risky; rescue ArgumentError => e; puts e.message; ensure; cleanup; end
raise ArgumentError, "bad input"
File.write("a.txt", "hi"); File.read("a.txt"); File.readlines("a.txt", chomp: true)
require "json"; JSON.parse(str, symbolize_names: true); obj.to_json
Gems and Rails
// gems, bundler and rails
gem install rails
bundle install
rails new app && rails server
rails g model Post title:string && rails db:migrate
rails console
Full Ruby documentation