Last active
February 22, 2017 02:33
-
-
Save smolin/c76f263c300ab1ced44cf41fbe982559 to your computer and use it in GitHub Desktop.
a simple cheatsheet for ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# constants | |
MYCONSTANT = 123 | |
# strings | |
myString = 'a b c' | |
myString = "a b c #{expression}' | |
# lists | |
myList = [1,2,3,4,5] | |
# some methods of list: | |
['select','map','each'] | |
# hash/dictionary/associative-array | |
myHash = {myKey => myValue, ...} | |
myHash = {mySymbol: myObject, ...} # shortcut for {:mySymbol => myObject} | |
# a function/procedure (arg parens optional) (myaArg2=100 indicates default) | |
def myFn myArg1,myArg2=100 | |
return myArg1 * myArg2 | |
end | |
# a code block | |
{|x| x**2}} | |
do |x| x**2 end | |
# lambdas and procs | |
myProc=lambda {|y| y**2} | |
# almost the same (no param count check; if it has a | |
# 'return' it will trigger a return in the calling context) | |
myProc=Proc.new {|y| y**2} | |
# call it | |
myProc.call | |
# use it in place of a code block | |
[my_list].select &myProc | |
# classes ("< MyParentClass" is optional) | |
# nb: "private" on a line by itself marks subsequent methods private (default | |
# is public, and there is a corresponding "public" indicator) | |
class MyClass < MyParentClass | |
$myGlobalVar = 5 | |
@@myClassVar = 6 | |
attr_reader :myVar | |
attr_writer :myOtherVar | |
attr_accessor :myThirdVar | |
def MyClass.myClassMethod | |
return @@myClassVar | |
end | |
def initialize myArg | |
@myInstanceVar = myArg | |
end | |
def myInstanceMethod | |
super myArg2,myarg3... | |
puts "myInstanceVar = #{@myInstanceVar}" | |
end | |
end | |
myObj = MyClass.new("zork") | |
myObj.description | |
# Modules | |
module MyModule | |
MYMODCONSTANT = 12345 | |
end | |
MyModule::MYMODCONSTANT # scope designator | |
# Require and Include and Extend | |
require 'date' # can now use Date.today | |
include Math # can now use cos() | |
extend # like 'include' but at the class level | |
# | |
module Foo ; end | |
class Fah | |
include Foo | |
end # Fah now has access to methods of Foo | |
# wtf? | |
numbers_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
strings_array = numbers_array.collect &:to_s | |
# | |
String.new # okay | |
Integer.new # error | |
# | |
i=5 # equals sign, no type | |
class person {} # no equals, yes type | |
# | |
public/private markers in class definitions. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment