π 2022-May-24 ⬩ βοΈ Ashwin Nanjappa ⬩ π·οΈ cheatsheet, ruby ⬩ π Archive
Below are notes I took while learning Ruby, written from the point of view of a Python programmer.
$ irb
irb(main):001:0> x = 10
irb(main):002:0> x
=> 10
$ ruby foobar.rb
$ sudo apt install ruby2.7-doc
$ ri <whatever you want>
$ ri print
print("Hello!\n")
print("Value of x is: ", x)
Note that unlike Python, print does not add spaces or newlines automatically. Spaces and newlines have to be explicitly specified. WYSIWYG strictly.
require "foo/bar"
require_relative "where/is/it"
.rb
Ruby file with its own named module
block inside it, inside whose namespace we can have variables, methods or classes.# foobar.rb
module FooBar
# Vars, methods, classes go here
def foobar(x, y)
end
end
# Accessed from another file as ...
require_relative "foobar"
FooBar.foobar(10, 20)
initialize
is the ctor. Instance variables have the @
prefix and cannot be accessed outside the class.class Foobar
def initialize(x, y)
@x = x
@y = y
end
def another_func()
end
end
attr_reader
definitions in the class:class Foobar
attr_reader :x
attr_reader :y
def initialize(x, y)
@x = x
@y = y
end
end
f = Foobar(10, 20)
f.x # Works!
self
to refer oneβs own methods in the class:class Foobar
def func1()
end
def func2()
self.func1()
end
end
x = []
y = ["foo", 1, nil]
x[0] = y[0]
x.append(y[2])
alist = [1, 2, 3]
for x in alist
print(x, "\n")
end
empty_hash = {}
ahash = {"x": 1, "y": 2}
ahash.each do |k, v|
print(k, v)
end
if ahash.key?("foobar")
print("Foobar present in hash")
end
"123".to_f
123.to_f
> x = 3.14
> x.to_i
=> 3
> x = 3.99
> x.round
=> 4
"x" == "x" # Always true
"x".equal?("x") # false
:
colon operator to create a symbol, a trick to have a single copy of literal strings::foo.equal?(:foo) # true
Object
, so available in every Ruby object.