Last active
August 29, 2015 14:04
-
-
Save afair/b436435021a49912e7aa to your computer and use it in GitHub Desktop.
Ruby Reference by Examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module MyModule | |
def module_method | |
end | |
end | |
class RubyRef < BaseClass | |
include MyModule | |
attr_reader :a | |
attr_writer :b | |
attr_accessor :c | |
def initialize(a, b, c) | |
@a = a | |
end | |
def numeric_literals | |
n = 123 + 1_000_000 + -5000 + 0777 + 0x0d + 0v1010101 + ?b + ?\n | |
n = 123456789012345235235 | |
n = 1234.4 + 1.02e23 + 4E20 + 4e+20 | |
end | |
def string_literals | |
['no interp', %q(no interp), "yo #{var}", %Q(interp "#tvxpression}"), %Q(intern)] | |
`command hello` || %x(command hello) | |
print <<"EOS" # "EOS" or 'EOS' or `EOS` | |
blah | |
EOS | |
end | |
def control_structures | |
if true | |
true | |
elsif false | |
false | |
else | |
nil | |
end | |
something() if true | |
something() unless false | |
end | |
def loops | |
loop do | |
break if done | |
end | |
while true | |
something | |
end | |
until true | |
something | |
end | |
begin | |
something | |
end while true | |
for var in expression | |
p var | |
end | |
def arrays | |
a = ['hi', 123, Time.new] + %w(nointerp words) + %W(interp a#{Time.new}z) | |
a[0] == a.first | |
a.size | |
a.reverse | |
a.sort {|a,b| a<=>b} | |
end | |
def hashes | |
h = {"key" => "value", symbol:123} | |
h["key"] | |
h.fetch("key") {|missing| missing.object_id } | |
h = Hash[ [a:, 1, :b, 2].collect { |v| | |
h = arr.each_with_object({}) { |v,h| h[v] = f(v) } | |
h = Hash[arr.collect { |v| [v, f(v)] }] | |
h = Hash[arr.zip(arr.map(&method(:f)))] | |
end | |
def enumerate_arrays_and_hashes | |
a.each { |element| puts element } | |
a.each_with_index { |element, index| puts element * index } | |
a.find_all {|e| e.even? } | |
a.grep(/regex/) {|match| match.upcase} # optional block | |
a.inject(initial) {|memo, element| memo + element} | |
total = [1,2,3].inject(&:+) | |
a.map {|e| e * 2 } | |
a.max - a.min {|a,b| a <=> b } | |
end | |
def ranges | |
(1..9) == (1...10) | |
(1..10).each { |i| puts i } | |
end | |
def exceptions | |
begin | |
raise Exception, "message" | |
rescue Exception => var | |
puts var | |
else | |
puts "completed without exception" | |
ensure | |
puts "always executed" | |
end | |
end | |
def files | |
puts File.read("filename") | |
File.open(filename, "r") { |f| f.gets } | |
IO.foreach(path) {|line| puts line } | |
array = IO.readlines(path) | |
end | |
def blocks | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment