Jan 29, 2015

Ruby notes



My discoveries:

print : echo bare text
p: print object as it as, with new line
puts: echo text with new line

alias create alias for existing method, var

ensure always executed at block termination

block comment
=begin 
=end

undef remove function definition


convention:
Eg: eql?
method with a question mark return a bool value

Eg: delete! (bang symbol)
method with exclamation ! indicates that it's destructive: change object than a copy

Eg: name=
method ends with = is a setter


block can be wrapped by "do .. end" or { }
run by "yield"
Check for existence via if block_given?

:symbol 
storage optimized string

Global names is from Kernel module


replace string once:
string['search']= 'replace'

replace all
string.gsub 'search', 'replace'

regex
string[/regex/]
regex replace uses the same syntax

string.split(/, /) you might guess

Object methods:
obj.to_s
obj.class

string.to_sym -> :symbol
num_string.to_i -> integer
range.to_a -> array

%w[ string1, ... ]
%i [ symbol1, ...]
[num1, ... ]

array << x # Add x to array (immuttable)

set operator: intersect &, diffeence -, union | 
array.join sep
array.shift

Hash.new(default_value)
hash.key?
hash.value?
hash.keys
hash.values

No comments:

Post a Comment

New comment