Output
puts "text" #outputs text followed by a newline to the console puts "#{exp}" #evaluates exp puts '#{exp}' #careful! single quotes do not do interpolation or evaluation of escape sequences such as \t, \n, etc
p foo calls puts foo.inspect instead of to_s (sometimes contains useful debugging information)
Creating Classes
class ClassName < SuperClass #constructor, array has a default value of [] def initialize(param, array = []) super @param = param #instance variable @array = array end #mutator function def val=(val) @val = val end #reader function def val @val end #index this class def[] (i) @array[i] end #bool method convention def vals_eql? @param == @val end #calling super def over_ridden_method(val) super(val) end attr_reader :array #creates accessor for array attr_writer :param #creates mutator method for param attr_accessor :val #creates accessor and mutator for val end
File Handling
File.open('file_name', 'opts')
- Operation List:
- 'r' : read only
- 'r+': read/write, starts at beginning of file
- 'w': write, truncates file to 0 or creates file if it doesn't exist
- 'w+': read/write, truncates file to 0 or creates file if it doens't exist
- 'a': write, appends to end of file
- 'a+': read/write, appends to end of file
- 'b': binary file
- 't': ascii text file
Common Data Types
Arrays
-collection of items, accessed by index.
arr = Array.new(old_array) arr = Array.new(size=0, obj=nil) #copies size objects nil times arr = Array.new(size) {|index| block} #value returned by block is stored for each index arr = ['1', 2, 3.0] #values may be of different types
Useful array methods:
arr.each arr.size arr[-1] #returns last item arr.slice(start, length) arr.slice(range)
Hash
-collection of key, value pairs
There are many ways to instantiate a hash. All of the following result in {”a” = 100, “b” = 200}:
Hash[“a”, 100, “b”, 200] Hash[“a”=> 100, “b” => 200] h = Hash.new(“Nope!”) h[“a”] = 100 h[“b”] = 200
new can take an argument that is returned when a key is not found.
h[“c”] returns “Nope!”
Useful hash methods:
h.keys h.values h.each_value h.each_key h.each_pair h.each
Branching
Ruby has the usual if, else, and switch constructs.
Every if must be paired with an end:
if condition statement end if condition statement else statement end
To use if on one line, use then:
if condition then stuff end
unless can be used to make lines simpler:
puts “Hello” unless x == 3 unless x == 3 puts “Hello”
Case statements are very powerful and flexible. One example below:
case num when 1 puts “Number 1!” when 2 puts “First loser!” else puts “Go home.” end
Enumeration (loops)
It is very idiomatic to avoid for or while loops in Ruby, although while loops of course still have a place.
Generally, iterations takes place over something that is Enumerable.
For example, as we see above, all collections should implement “each”, which is the most common looping mechanism.
arr.each do |element| puts element.to_s end h.each do |key, value| puts “#{key} = #{value}” end
For looping between two integers:
1.upto(3) do |x| puts x.to_s end
outputs:
1
2
3
For instances where the number of times is important but the index is not:
3.times { puts “Hello!” }
**note that { } is equivalent to do end. do end is preferable for multi-line blocks.
Useful utilities
Random.rand(max) #returns a random int between 0 and max, excluding max.
any object can have its methods inspects by called obj.methods.
Any class can be edited on the fly to include new methods. This is called opening a class:
class Integer def doubled self * 2 end end
More Advanced, but useful features:
mixins and modules