Skip to content

Instantly share code, notes, and snippets.

@cwli24
Last active April 20, 2022 07:06
Show Gist options
  • Save cwli24/9091ed959838f20f3defb8a97a8624ee to your computer and use it in GitHub Desktop.
Save cwli24/9091ed959838f20f3defb8a97a8624ee to your computer and use it in GitHub Desktop.
Ruby syntax 101 guide
#!/usr/bin/ruby -W0
BEGIN {
puts "This block will always run first."
print <<EOF
----------------
EOF
} # notice EOF cannot be indented
END {
print <<"up2u"
----------------
This block will always run last.
up2u
}
$global_variable = "Everything in Ruby is an object."
GLOBALCONSTANT = "Constants begin with an uppercase."
class Customer
@@class_variable = "Must be initialized before any usage or error."
@instance_variable = "Notice the 1 or 2 @ in front."
CLASSCONSTANT = "Constants cannot be defined in methods."
def initialize(_name) # constructor equivalent
@name = _name # local vars are defined and scoped inside methods
end
def function_call
# hash is used to comment but also access value of any variable or constant
puts "This customer is #@name."
end
end
#emptyClass = Customer.new <- would work if there wasn't an initialize defined
filled_class = Customer.new("Bob")
filled_class.function_call
=begin
*These 6 keyword variables behave like constants:
self (within method context), true, false, nil,
__FILE__, and __LINE__
*Fixnum are integers within [-2^30, 2^(30-1)] or [-2^62, 2^(62-1)]. Integers outside range are stored in Bignum class.
*(") vs (') matters in Ruby. The former allows substitution and escape, but the latter is stricter.
=end
_a, _b = 2, 2.0
print "#{_a == _b}, #{_a.eql?(_b)}\n" # true, false
# FYI, running code without "-W0" will generate warnings here because we're changing constants
COUNT = 0
module CannotBeInstances
COUNT = 1
::COUNT += 1 # :: can refer to methods too
COUNT += 1
end
print COUNT,', ',CannotBeInstances::COUNT,"\n" # 1, 2
# In addition to if...elsif...else
_c = (1+1)==2
puts '1 + 1 = 2' if _c
unless _c
puts "This won't execute because c is true."
else
# puts "This will."
end
puts "This won't either." unless _c
_d = 5
case _d
when 1; puts "One-liner style"
when 3, 4 then puts "Multiple case match"
when 6..8 then puts "Range includes 8"
when 10...13; puts "Range excludes 13"
else
puts _d
end
# ...while... and ...until... are intuitive with other languages
# so are break and next (continue-equivalent)
for i in 0...1
puts "Doesn't create new scope for local variables."
# redo <- will restart this iteration (infinite loop)
# retry if i > 0 <- will reset i completely / restart iterator (infinite loop)
end
(0..0).each do |i|
puts "Does create new scope."
end
begin
"do_something" # assume exception raised
rescue
# handle error
retry # restart from begin
end
def do_not_cap_method(var1, var2 = "default")
puts "#{var1} and #{var2}."
end
do_not_cap_method "Define method before calling"
do_not_cap_method "Capping method name confuses Ruby", "with constants.."
def default_return
_last_assignment_value = 123
end
puts default_return # 123, even though no return statement
def multiple_args(*params)
for i in 0...params.length
puts "param #{i}: #{params[i]}"
end
end
multiple_args "Dogecoin", "is a bad meme."
def private_by_default
puts "When defined outside class."
end
class AccessClassMethod
def public_by_default
puts "When defined inside class."
end
def AccessClassMethod.without_instance
puts "This is a class method."
end
end
AccessClassMethod.without_instance
alias some_other_name private_by_default
some_other_name # creates a copy of the method (not reference to same)
undef some_other_name
# Method+block pair should use the same name.
def using_blocks(&block)
yield "Hi" # this is one way to invoke a block
puts "Inside the method."
block.call "Bye" # this is another way to invoke
end
using_blocks {|s| puts "#{s} from the block."}
module Trig
PI = 3.141592654
def Trig.sin(x) # Just like class method declarations
end
end
# $LOAD_PATH << '.' <- to load modules in other .rb files
# require 'trig' <- alternatively, use require_relative
_e = Trig.sin(Trig::PI/4)
class Calculus
include Trig # this embeds the module into class
# including multiple modules in a class is Ruby's version of multiple inheritance, called mixins
def print_pi
puts Trig::PI
end
end
puts %Q[Equivalent to double-quoted string.]
puts %q<Equivalent to single-quoted string.>
puts %x!ls! # == `ls` command output
_f = String.new("Find long list of string functions at https://www.tutorialspoint.com/ruby/ruby_strings.htm")
puts _f.downcase
_g = Array.new
puts _g.size
_g = Array.new(20)
puts _g.length
_g = Array.new(10) {|n| n = n*2} # or Array(0..9) too
print _g, "\n"
# For a list of array methods: .../ruby_arrays.htm
_h = Hash.new "This is the default value." # if no default provided, default is nil
puts _h["key_that_doesnt_exist"] # prints the above
_h = {'1' => "Don't rely on insertion order for Hashes",
'2' => ".../ruby_hashes.htm for list"}
puts "#{_h.values}"
_time = Time.new
puts "Current time: " + _time.inspect
p _time.to_a # [sec,min,hour,day,month,year,wday,yday,isdst,zone]
=begin
puts Time.local(*(_time.to_a))
puts Time.now.to_i # number of seconds since epoch
puts Time.at(Time.now.to_f)
More at .../ruby_date_time.htm
NOTICE: "This class may be unable on your system to represent dates before 1970 or after 2038."
=end
p ('a'..'e').to_a
p ('bra'..'bro').to_a.include?('brb')
# p ('bra'..'bro') === 'brb' <- same as above
p (1..5).reject {|n| n > 3}
_i = [1, 2, 3, 4, 5]
_j = _i.collect {|n| 10*n} # .collect is an iterator like .each
p _j
puts "Enter a string: "
_str = gets
putc _str # one char
putc "\n"
File.open("main.rb", "r") do |_file|
# See .../ruby_input_output.htm
end
class MyFavoriteException < StandardError
attr_reader :reason
def initialize(_reason)
@reason = _reason
end
end
_k = "nonexistent_file.txt"
begin
_file = open(_k)
if _file
puts "Opened successfully."
end
raise MyFavoriteException.new("...just because :)")
rescue MyFavoriteException => e
puts "You thought. Sike.", e.reason
rescue
puts "Dang. Retry."
_k = "main.rb"
retry
else
puts "Only if there were no errors."
ensure
puts "This will always execute."
end
catch :thisIsLikeGotoInC do
puts "Hah, got em."
throw :thisIsLikeGotoInC
puts "This won't execute"
end
@cwli24
Copy link
Author

cwli24 commented Apr 20, 2022

I gathered this information from Tutorials Point, and I'm unsure which version they're using, so some things may be outdated.
This is meant as a quick reference for new Ruby learners with previous general experience of other languages, as only the basics are shown here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment