Skip to content

Instantly share code, notes, and snippets.

@itarato
Last active March 20, 2025 13:48
Show Gist options
  • Save itarato/d16e627bf012d477b16f1ddb615668e3 to your computer and use it in GitHub Desktop.
Save itarato/d16e627bf012d477b16f1ddb615668e3 to your computer and use it in GitHub Desktop.
Ruby (Random) Basics

Short circuit

return if user.nil?

Multiline strings

<<STR
Long
Text
STR

Instance / class attr accessors

class User
	attr_reader(:id)
	attr_writer(:name)
	attr_accessor(:city)

	class << self
		attr_reader(:service_id)
	end
end

Blocks

def with_log(&block)
	log("Call starts")
	block.call
end
def with_log
	log("Call starts")
	yield
end
def delete(user)
	yield(user) if block_given?
	DB.delete(user)
end

Scope

def save_user(user)
	user.save
rescue SaveError => err
	log_error(err)

	if user.validation_on?
		user.turn_off_validation
		retry
	end
rescue => err
	log_error(user)
ensure
	log(user)
end

Block

begin
rescue
ensure
end

Return vs next

def one
	return 1
end
[0, 1, 2].each { next if it.odd?; puts(it) }

Redo

p(10.times.map do |i|
	die_1 = rand(1..6)
	die_2 = rand(1..6)

	redo unless die_1 + die_2 == 7
	[die_1, die_2]
end)

Iterators

for n in [1, 2, 3]
  p(n)
end
10.times { puts(it) }
10.upto(20) { puts(it) }

Enumerable

[1, 2, 3].each do |i|
	p(i)
end
doubled_evens = 10.times.filter_map do
	next false if it.odd?
	it << 1
end
[1, 2, 3][-1]

Enumerator

def fibonacci
	Enumerator.new do |yielder|
		yielder.yield(0)
		
		a = 0
		b = 1

		loop {
			a, b = b, a + b
			yielder.yield(a)
		}
	end
end

fibonacci.take(10)

Safe navigation

user_or_nil&.save

GC

GC.start
ObjectSpace.count_objects

Lambda / Proc / Block

succ = Proc.new { |x| x + 1 }
succ = lambda { |x| x + 1 }
succ = -> (x) { x + 1 }

Benchmark

require 'benchmark/ips'

Benchmark.ips do |x|
  x.report("String +") { "Hello, " + "world!" }
  x.report("String <<") { str = "Hello, "; str << "world!" }
  x.report("String interpolation") { "Hello, #{'world!'}" }

  x.compare!
end

Dump IR

ruby --dump=insns <source>.rb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment