Created
March 15, 2012 16:55
-
-
Save bootandy/2045262 to your computer and use it in GitHub Desktop.
basics of 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
#Hashes: | |
def test_combining_hashes | |
hash = { "jim" => 53, "amy" => 20, "dan" => 23 } | |
new_hash = hash.merge({ "jim" => 54, "jenny" => 26 }) | |
def default_value_hash | |
hash2 = Hash.new("default") | |
hash2[:one] = 1 | |
assert_equal 1, hash2[:one] | |
assert_equal "default", hash2[:two] | |
assert_equal "default", hash2[:something_not_existing] | |
# Crazy block - runs code when key not in hash and creates an empty array for you | |
def test_default_value_with_block | |
hash = Hash.new {|hash, key| hash[key] = [] } | |
hash[:one] << "uno" | |
hash[:two] << "dos" | |
assert_equal ["uno"], hash[:one] | |
assert_equal ["dos"], hash[:two] | |
assert_equal [], hash[:three] | |
hash.keys # get hash keys | |
end | |
#Arrays: | |
def test_slicing_arrays | |
array = [:peanut, :butter, :and, :jelly] | |
# Please note: | |
#[ start, LENGTH] | |
#[ start .. END ] | |
assert_equal :peanut, array.first | |
assert_equal [:peanut], array[0,1] | |
assert_equal [:peanut, :butter], array[0,2] | |
assert_equal [ :and, :jelly], array[2,2] | |
assert_equal [ :and, :jelly], array[2,20] | |
assert_equal [], array[4,0] | |
assert_equal [], array[4,100] | |
assert_equal nil, array[5,0] | |
assert_equal [:peanut, :butter, :and], array[0..2] | |
assert_equal [:peanut, :butter], array[0...2] | |
assert_equal [:and, :jelly] , array[2..-1] | |
def test_pushing_and_popping_and_shifting_arrays | |
array = [1,2] | |
array.push(:last) | |
assert_equal [1,2,:last], array | |
popped_value = array.pop | |
assert_equal :last, popped_value | |
assert_equal [1,2], array | |
array = [1,2] | |
array.unshift(:first) | |
assert_equal [:first, 1,2], array | |
shifted_value = array.shift | |
assert_equal :first, shifted_value | |
assert_equal [1,2], array | |
end | |
def array_sum | |
scores = [1,2] | |
scores.inject(:+) | |
end | |
#Strings | |
def test_flexible_quotes_can_handle_multiple_lines | |
long_string = %{ | |
It was the best of times, | |
It was the worst of times. | |
also handles ' and " | |
can also start with a ( or ! | |
} | |
puts long_string | |
puts long_string.length | |
end | |
# in ruby '=' is a reference assignment not set equal to. | |
def be_careful_of_shovel | |
# using += - standard behaviour: | |
original_string = "Hello, " | |
hi = original_string | |
there = "World" | |
hi += there | |
assert_equal "Hello, ", original_string | |
# using >> - original_string is modified as it is referenced via 'hi' | |
original_string = "Hello, " | |
hi = original_string | |
there = "World" | |
hi << there | |
assert_equal "Hello, World", original_string | |
end | |
def test_double_quoted_string_interpret_escape_characters | |
string = "\n" | |
assert_equal 1, string.size | |
a = 10 | |
str = "hi #{a+1}" | |
assert_equal "hi 11", str | |
end | |
def test_single_quoted_string_do_not_interpret_escape_characters | |
string = '\n' | |
assert_equal 2, string.size | |
a = 10 | |
str = 'hi #{a+1}' | |
assert_equal 'hi #{a+1}', str | |
end | |
def test_single_quotes_sometimes_interpret_escape_characters | |
string = '\\\'' | |
assert_equal 2, string.size | |
def test_you_can_get_a_substring_from_a_string | |
string = "Bacon, lettuce and tomato" | |
assert_equal 'let', string[7,3] # Position 7 forward 3 | |
assert_equal 'let', string[7..9] # Position 7 to position 9 | |
def test_strings_can_be_split | |
string = "Sausage Egg Cheese" | |
words = string.split | |
assert_equal ["Sausage", "Egg", "Cheese"], words | |
assert_equal ["Sausage", "Egg", "Cheese"].join(" ") ,string | |
string = "the:rain:in:spain" | |
words = string.split(/:/) #regexp | |
assert_equal ["the","rain","in","spain"], words | |
def regexp | |
grays = /(James|Dana|Summer) Gray/ | |
assert_equal "James Gray", "James Gray"[grays] | |
assert_equal "Summer", "Summer Gray"[grays, 1] | |
def test_scan_is_like_find_all | |
assert_equal ["one","two","three"], "one two-three".scan(/\w+/) | |
end | |
def test_sub_is_like_find_and_replace | |
assert_equal "one t-three", "one two-three".sub(/(t\w*)/) { $1[0, 1] } | |
end | |
def test_gsub_is_like_find_and_replace_all | |
assert_equal "one tw-th", "one two-three".gsub(/(t\w*)/) { $1[0, 2] } | |
end | |
#Class design: | |
class Dog | |
def name | |
"Fido" | |
end | |
def bark | |
"WOOF" | |
end | |
# to_str means I can be treated like a string: | |
def to_str | |
"Dog" + name + bark | |
end | |
private | |
def tail | |
"tail" | |
end | |
# another way to do private: | |
def my_private_method | |
"a secret" | |
end | |
private :my_private_method | |
end | |
def test_calling_methods_in_other_objects_require_explicit_receiver | |
rover = Dog.new | |
assert_equal "Fido", rover.name | |
end | |
def test_calling_private_methods_in_other_objects | |
rover = Dog.new | |
assert_raise(NoMethodError) do | |
rover.tail | |
end | |
end | |
# Inheritance & super | |
class BullDog < Dog | |
def bark | |
super + ", GROWL" | |
#super.name is not allowed - can only super the same name method | |
end | |
@@static_variable_double_at | |
def self.class_method2 | |
:another_way_to_write_static_class_methods | |
end | |
class << self | |
def another_class_method | |
:still_another_way_to_do_static_class_methods | |
end | |
end | |
end | |
def BullDog.wag | |
:this_is_how_you_do_static_class_methods | |
end | |
class Dog2 | |
# @name is private we can not read it | |
def set_name(a_name) | |
@name = a_name | |
end | |
# Now we provide a getter for it | |
def set_name2(a_name) | |
@name2 = a_name | |
end | |
def name2 | |
@name2 | |
end | |
# Auto provide getter for name3 | |
attr_reader :name3 | |
def set_name(a_name) | |
@name3 = a_name | |
end | |
# Auto provide getter AND setter for name4 | |
attr_accessor :name4 | |
# Constructor | |
def initialize(initial_name) | |
@name5 = initial_name | |
end | |
end | |
# Mixins: | |
module Nameable # Its a bit like an abstract class | |
# Add this functionality to any class it is added to: | |
def set_name(new_name) | |
@name = new_name | |
end | |
def here | |
:i_get_overridden | |
end | |
end | |
class DoggyMixin | |
include Nameable # Use the above mixin | |
attr_reader :name | |
def initialize | |
@name = "Fido" | |
end | |
def bark | |
"WOOF" | |
end | |
def here | |
:i_have_priority | |
end | |
end | |
#Modules: | |
module Jims | |
class Dog | |
def identify | |
:jims_dog | |
end | |
end | |
end | |
module Joes | |
class Dog | |
def identify | |
:joes_dog | |
end | |
end | |
end | |
def test_you_can_reference_nested_classes_using_the_scope_operator | |
fido = Jims::Dog.new | |
rover = Joes::Dog.new | |
assert_equal true, fido.class != rover.class | |
assert_equal [:Dog], Jims.constants | |
end | |
# Keywords: | |
# Constants must be in CAPITALS - accessed with :: | |
# unless x === if !x | |
# next === continue in loops | |
# Exception handling: | |
def exception_handling | |
begin | |
# 'raise' and 'fail' are synonyms | |
raise MySpecialError, "My Message" | |
rescue MySpecialError => ex | |
result = :exception_handled | |
end | |
ensure | |
result = :like_finally | |
end | |
result | |
end | |
# How to Iterate: | |
def are_values_below_zero(*args) | |
if args.any? { |x| x <=0 } | |
raise Error, 'Size below or equal to 0 Error' | |
end | |
end | |
def iterate() | |
array = [1, 2, 3] | |
array.each do |item| | |
sum += item | |
end | |
# stepping backwards: 999.downto(100) | |
another_array = array.map { |item| item + 10 } # collect and map are synoyms | |
assert_equal [11,12,13], new_array | |
even_numbers = array.select { |item| (item % 2) == 0 } # find_all and select are synoyms | |
assert_equal [2,4,6], even_numbers | |
# is there a 1 in here? | |
array.any? { |x| x == 1} | |
array.include?(1) | |
# find returns first value found | |
x = array.find { |item| item > 1 } | |
assert_equal 2, x | |
# inject is like 'fold' we have to provide the first value | |
result = [2, 3, 4].inject(0) { |sum, item| sum + item } | |
assert_equal 9, result | |
result2 = [2, 3, 4].inject(1) { |sum, item| sum * item } | |
assert_equal 12, result2 | |
# how 2 hold on to the index in a map - use: each_with_index | |
# file.each_with_index.map { |line, index| score_name line.strip * index } | |
end | |
def while_loop | |
people = [] | |
do | |
info = gets.chomp | |
people += [Person.new(info)] if not info.empty? | |
while not info.empty? | |
end | |
# File IO | |
def file_io() | |
File.open("example_file.txt") do |file| | |
upcase_lines = file.map { |line| line.strip.upcase } | |
assert_equal ["THIS","IS","A","TEST"], upcase_lines | |
end | |
end | |
# read in one block: | |
#file = File.open("path-to-file.tar.gz", "rb") | |
#contents = file.read | |
# read in from 'this' directory: | |
#f = File.open(File.join( File.dirname(__FILE__), 'data.html') ) | |
# blocks: | |
def method_with_block | |
if block_given? | |
result = yield # Call to yield means method must be called with a block | |
result | |
else | |
:no_block | |
end | |
end | |
def test_methods_can_take_blocks | |
yielded_result = method_with_block { 1 + 2 } | |
assert_equal 3, yielded_result | |
assert_equal :no_block, method_with_block | |
end | |
def method_with_block_arguments | |
yield("Jim") | |
end | |
def test_blocks_can_take_arguments | |
result = method_with_block_arguments do |argument| | |
assert_equal "Jim", argument | |
end | |
end | |
def many_yields | |
yield(:peanut) | |
yield(:butter) | |
yield(:and) | |
yield(:jelly) | |
end | |
def test_methods_can_call_yield_many_times | |
result = [] | |
many_yields { |item| result << item } | |
assert_equal [:peanut,:butter, :and,:jelly], result | |
end | |
def lambdas | |
add_one = lambda { |n| n + 1 } | |
assert_equal 11, add_one.call(10) | |
# Alternative calling sequence | |
assert_equal 11, add_one[10] | |
end | |
def blocks_and_lambdas | |
make_upper = lambda { |n| n.upcase } | |
result = method_with_block_arguments(&make_upper) | |
assert_equal "JIM", result | |
end | |
def method_with_explicit_block(&block) | |
block.call(10) | |
end | |
def test_methods_can_take_an_explicit_block_argument | |
assert_equal 20, method_with_explicit_block { |n| n * 2 } | |
add_one = lambda { |n| n + 1 } | |
assert_equal 11, method_with_explicit_block(&add_one) | |
end | |
# cool time function call with | |
# time_it do | |
# code | |
# end | |
def time_it | |
start = Time.now | |
yield | |
puts "Time taken: #{Time.now - start}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment