Code Yarns β€πŸ‘¨β€πŸ’»
Tech Blog ❖ Personal Blog

Ruby Cheatsheet

πŸ“… 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"
# 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)
class Foobar
  def initialize(x, y)
    @x = x
    @y = y
  end

  def another_func()
  end
end
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!
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
:foo.equal?(:foo)  # true

References


Β© 2022 Ashwin Nanjappa β€’ All writing under CC BY-SA license β€’ β€’ πŸ“§