Skip to content

Instantly share code, notes, and snippets.

@anoxic
Last active December 26, 2017 06:48
Show Gist options
  • Save anoxic/5409480 to your computer and use it in GitHub Desktop.
Save anoxic/5409480 to your computer and use it in GitHub Desktop.
Ruby notes
--
Files
Get a file f = File.new("testfile")
Get line number f.lineno # note: you can't seek with lineno
Get a line f.gets # equal to the var $_
Read each line f.each { |line| puts "#{f.lineno}: #{line}" }
# note: after using .each on a file once, you must .rewind the file
Into an array arr = f.readlines
Get a line quickly arr[3]
# like .each, you must .rewind after running .readlines once, unless place it in a variable
--
Arrays/Hashes
Array []; [1, 'a', /^A/]
A quick array Array.new(3){ |index| index ** 2 } # => [0, 1, 4]
Access an array arr[0]
Sort an array arr = arr.sort; arr.sort!
Sort in reverse sort!.reverse; sort! { |x,y| y <=> x } # The second is more process efficient
Hash {}; { "a" => 100, "b" => 200 }; { a: 100, b: 200 }
A quick hash h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" }
h["c"] #=> "Go Fish: c"
h["d"] #=> "Go Fish: d"
h.keys #=> ["c", "d"]
Note: arrays (and any object you modify) can sometimes be confusing when you change them. Consider:
a = []; b = a; b << 1; print a
#=> [1]
This is because ruby pointed a and b to the same array object: a.object_id == b.object_id... You really wanted:
a = []; b = a.dup
--
Loops/Iterators
While while a < b { a += 1 }
Until until a > b { a += 1 }
For for num in 1..10
for num in 1...11
for item in arr
Loop i = 0; loop { i += 1; puts i; break if i == 10 }
Each arr.each { |v| puts v }
hash.each { |k,v| puts k, v }
Times 10.times
--
Control flow
If if hungry
puts "I hunger"
elsif tired
puts "I tire"
else
puts "I am neither hungry nor tired"
end
Unless unless hungry
puts "I am not hungry"
end
Shorthand puts "I'm hungry" if hungry
puts "I'm no hungry" unless hungry
There are several ways one can connect to a DB (in this case SQL) in Ruby --
ActiveRecord - http://www.rubydoc.info/gems/activerecord/4.2.0/frames
- http://blog.aizatto.com/2007/05/21/activerecord-without-rails/
DataMapper - http://datamapper.org/why.html
Sequel - http://sequel.jeremyevans.net/
MySQL2 - https://github.com/brianmario/mysql2
Arel - https://github.com/rails/arel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment