Skip to content

Instantly share code, notes, and snippets.

@jordanpoulton
Created March 4, 2013 17:59
Show Gist options
  • Save jordanpoulton/5084131 to your computer and use it in GitHub Desktop.
Save jordanpoulton/5084131 to your computer and use it in GitHub Desktop.
Practise from Well grounded Rubyist
class C
puts "Just started class C"
puts self
module M
puts "Nested module C::M"
puts self
end
puts "back in the outer level of C:"
puts self
end
class D
def x
puts "Class D, method x:"
puts self
end
end
d = D.new
d.x
puts "That was a call to x by #{d}"
obj = Object.new
def obj.show_me
puts "Inside Singlton method show_me of #{self}"
end
obj.show_me
puts "Back from call to show_me by #{obj}"
class E
def E.no_dot #Also self.no_dot
puts "As long as self is E, you can call this method with no dot"
end
no_dot
end
#E.no_dot
class F
def x
puts "This is a method 'x'"
end
def y
puts "This is a method 'y', abdout to call x without a dot"
x
end
end
f = F.new
f.y
class Person_1
attr_accessor :first_name, :middle_name, :last_name
def whole_name
n = first_name + " "
n << "#{middle_name}" if middle_name
n << last_name
end
end
goliath = Person_1.new
goliath.first_name = "Goliath"
goliath.last_name = "Black"
puts "Goliath's whole name: #{goliath.whole_name}"
goliath.middle_name = "Alan"
puts "David's whole name: #{goliath.whole_name}"
class G
puts "Just inside class definition block. Here's self"
p self
@v = "I'm an instance variable at the top level of class G"
puts "And here's the instance variable @v, belonging to #{self}"
p @v
def show_var
puts "Inside an instance method definition block, here's self:"
p self
puts "And here's the instance variable @v, belonging to #{self}"
p @v
end
end
g = G.new
g.show_var
h = 0
def top
puts "top level method TOP"
end
class I
h = 1 #EACH H KNOWS NOTHING OF THE OTHERS
def self.x
h = 2
puts "I.x; h = #{h}"
end
def m
h = 3
puts "I-object.m; h = #{h}"
end
def n
h = 4
puts "I-object.n; h = #{h}"
end
puts h
end
puts "Top level h = #{h}"
I.x
j = I.new
j.m
j.n
class K
def x(value_for_a, recurse=false)
a = value_for_a
print "
Here's the object_id string for 'self': "
p self.object_id
puts "and here's a: "
puts a
if recurse
puts "recursing by calling myself..."
x("second value for a")
puts "Back after recursion, here's a:"
puts a
end
end
end
k = K.new
k.x("First value for a")
k.x("First value for a with recursion", true)
class Violin
class String
attr_accessor :pitch
def initialize(pitch)
@pitch = pitch
end
end
def initialize
@e = String.new("E")
@a = String.new("A")
end
end
v = Violin.new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment