#OOP ####
Everything is an object in ruby.
Classes are objects in a ruby interpreter. Classes are object blueprints.
Methods in classes shadow. To call superclass: super.
#Method ####
def method_name(*args) { #block }
if block_given?
yield
end
end
#lookup chain , , , ,
#method calls
#shorthand method call (1.9+)
#calling objects methods
["A", "b", "foo"].map &:upcase #=> ["A", "B", "FOO"]
#calling method in scope on the objects
["foo", "bar", 1].each &method(:p) #=> ["foo", "bar", 1]
module Foo; def self.twice x; x * 2 end end; [1,2,3].map &Foo.method(:twice)
#dynamically defined methods ####
(class << obj; self; end).define_method(:mname, lambda { "do schtuff" })
#Module ####
include MyModule #mixes module into class
extend MyModule #mixes module into instance
# require for installed gems
# require uses your $LOAD_PATH to find the files.
require 'pry'
# require_relative for local files
# equals: require (File.expand_path('path', File.dirname(__FILE__)))
require_relative './planet_tests.rb'
#adding directory (of this file) in LOAD_PATH
$:.unshift File.dirname(__FILE__)
#Array ####
#delimiters
%w ( 1 2 3 4 5 ) == ["1","2","3","4","5"]
#Numbers ####
!Representation doesn't affect the value
# Hexadecimal
# hex string to value
"ff".hex #=> 255
"e0".to_i(16) #=> 224 integer
# integer to hex
224.to_s(16) #=> e0
# int array to hex (CSS colors) (sprintf shorthand)
"\#%02X%02X%02X" % [255,255,255] # => "#FFFFFF"
sprintf("\#%02X%02X%02X", *[255,255,255]) # => "#FFFFFF"
# int to padded string (if too small) - sprintf
"%02d" % 9 # => "09"
"%02d" % 29 # => "29"
# map chars to/from codes
>> "45".chars.map { |c| c.ord.to_s(16) }.join
=> "3435" (http://eval.in/17034)
>> "3435".scan(/\d{2}/).map(&:hex).map(&:chr).join
=> "45" (http://eval.in/17035)
# Binary
# integer to binary
22.to_s(2) #=> "10110"
" %011b" % 9 #=> "00000001001"
# binary string to integer
"11110".to_i(2) #=> 30
#bitwise inversion
~0b1001 #=> -10
~20 #=> -21
#bitwise or
10 | 0b0101 #=> 15
# booleans ####
# No object class or type boolean
# Constant True
> TRUE
=> true
# string to boolean
> eval "true"
=> true
#Regexp ####
# match atom(s)
"as9ifooTTwem,as".match(/\d[a-z]+/).to_s #=> "9ifoo"
"9999murble.239%" =~ /[a-z]+/; $~.to_s #=> "murble"
# word count in string
"at foo or at bar".downcase.scan(/\w+/).each_with_object(Hash.new(0)) {|w,h| h[w] += 1 }
# Strings ####
# delimiters
%q(sum" string) == "sum\" string"
#interpolation
"Number one: #{winner_arr[0].to_s} !!" #string interpolation => "Number one: Casimir !!"
# multiline string def heredoc
str= <<-ADDR
John Doe
12345 Boulevard
City 55555
ADDR
#Blocks ####
#calling a block with enumerable members (from bitstring-gem)
def each(&block)
self.length.times { |bit| block.call(self[bit]) }
self
end
#Proc ####
Proc.new { puts "Hello!" }.call
#block to proc
blk = { ... }; &blk.call
#File IO ####
#load a file to a str
# read file line-by-line
File.foreach(filename_str){ |ln| ln = ln + getWord(); }
# read first line of file
File.open(fn) {|f| f.readline(0) }
#Source files ####
#set encoding of ruby source files on the first line with:
#encoding: utf-8
#Rubygems ####
#Setting RUBYLIB env var (if ruby cannot require gems)
#in bash:
export RUBYLIB="/lib/mylibs/${RUBYLIB:-""}"
#ruby option flag
ruby -I/lib/mylib/thislib
#in ruby code (adding directory to $LOAD_PATH
$:.unshift File.join( %w{ /lib mylib } )
# Debian and gems: `require': no such file to load -- mkmf (LoadError)
# - install the ruby-dev package from apt to get headers
sudo apt-get install ruby1.9.1-dev
# Syntax Checker ####
#check if the files in dir are ruby (ruby-crunchbang or .rb and passes syntax check):
# encoding: utf-8
puts Dir["*"].select{ |fn|
if !!`file "#{fn}"`[/text/] # non-binary?
( File.open(fn) {|f| !!f.readline[/#!.*ruby/] } || !!fn[/.rb/] ) && !!`ruby -c #{fn}`[/Syntax OK/]
else
false
end
}