User:Jarle Pahr/Ruby
http://www.sapphiresteel.com/The-Book-Of-Ruby
http://rubyinstaller.org/downloads/
Ruby glossary: http://www.codecademy.com/glossary/ruby
Ruby: https://www.ruby-lang.org/en/documentation/
Poignant guide to Ruby: slav.uniqpath.com/poignant-guide/book/chapter-1.html
Ruby documentation: https://www.ruby-lang.org/en/documentation/
Gems
rest-client
json
Hashes
http://www.ruby-doc.org/core-1.9.3/Hash.html
Examples
Get input:
user_input = gets.chomp
Search for substring in string:
string.include? "substring"
Convert to uppercase:
string.upcase!
Define a class:
class Person: attr_accessor :id, :first_name, :last_name end
Create instance of class:
person = Person.new
Get HTTP response:
require 'rest-client' response = RestClient.get base_url + "/names/", headers=headers
Show JSON content:
JSON.pretty_generate variable
For loop:
for num in 1...10 puts num end
"Each" iterator:
object.each { |item| # Do something }
or
object.each do |item| # Do something end
Do loop:
i = 0 loop do i += 1 print "#{i}" break if i > 5 end
Times iterator:
numberoftimes.times{do something}
Split string:
words = text.split(" ")
Hash tables
rocket notation:
hash = { key1 => value1, key2 => value2}
with symbols:
hash = {:symbol1 => value1, :symbol2 => value2}
new symbol notation:
hash = {key1: value1,key2: value2}
select:
good_movies = movie_ratings.select{|k,v| v >3}
Iterate over keys only:
movie_ratings.each_key {|k| puts k}
Delete from hash:
hashtable.delete(key)
Check if an object responds to a method:
object.respond_to?(:methodname)
Shoveling:
[1, 2, 3] << 4
Collect: Applies an expression to all elements in an array.
doubled_fibs = fibs.collect {|num| num *2}
Yield parameter to block:
def double(par) yield par end
double(2) {|x| x=2*x}
Inheritance:
class DerivedClass < BaseClass # Some stuff! end