Skip to content

Commit

Permalink
shallow/deep copy + binding example
Browse files Browse the repository at this point in the history
  • Loading branch information
brownman committed May 2, 2011
1 parent f5d3a49 commit 3b71379
Show file tree
Hide file tree
Showing 6 changed files with 387 additions and 0 deletions.
20 changes: 20 additions & 0 deletions bin/binding.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
puts 'get the value of @secret in the context of vX'
class Demo

def initialize(n)
@secret = n
end
def getBinding
return binding()
end
end

k1 = Demo.new(99)
b1 = k1.getBinding
k2 = Demo.new(-3)
b2 = k2.getBinding

p eval("@secret", b1) #=> 99
puts eval("@secret", b2) #=> -3
eval("@secret").inspect #=> nil

118 changes: 118 additions & 0 deletions bin/eval.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
#!/usr/local/bin/ruby

#######################################################
#
# Ruby interactive input/eval loop
# Written by matz (matz@netlab.co.jp)
# Modified by Mark Slagell (slagell@ruby-lang.org)
# with suggestions for improvement from Dave Thomas
# (Dave@Thomases.com)
#
#######################################################
#
# NOTE - this file has been renamed with a .txt extension to
# allow you to view or download it without the rubyist.net
# web server trying to run it as a CGI script. You will
# probably want to rename it back to eval.rb.
#
#######################################################

module EvalWrapper

# Constants for ANSI screen interaction. Adjust to your liking.
Norm = "\033[0m"
PCol = Norm # Prompt color
Code = "\033[1;32m" # yellow
Eval = "\033[0;36m" # cyan
Prompt = PCol+"ruby> "+Norm
PrMore = PCol+" | "+Norm
Ispace = " " # Adjust length of this for indentation.
Wipe = "\033[A\033[K" # Move cursor up and erase line

# Return a pair of indentation deltas. The first applies before
# the current line is printed, the second after.
def EvalWrapper.indentation( code )
case code
when /^\s*(class|module|def|if|case|while|for|begin)\b[^_]/
[0,1] # increase indentation because of keyword
when /^\s*end\b[^_]/
[-1,0] # decrease because of end
when /\{\s*(\|.*\|)?\s*$/
[0,1] # increase because of '{'
when /^\s*\}/
[-1,0] # decrease because of '}'
when /^\s*(rescue|ensure|elsif|else)\b[^_]/
[-1,1] # decrease for this line, then come back
else
[0,0] # we see no reason to change anything
end
end

# On exit, restore normal screen colors.
END { print Norm,"\n" }


##############################################################
# Execution starts here.
##############################################################

indent=0
while TRUE # Top of main loop.

# Print prompt, move cursor to tentative indentation level, and get
# a line of input from the user.
if( indent == 0 )
expr = ''; print Prompt # (expecting a fresh expression)
else
print PrMore # (appending to previous lines)
end
print Ispace * indent,Code
line = gets
print Norm

if not line
# end of input (^D) - if there is no expression, exit, else
# reset cursor to the beginning of this line.
if expr == '' then break else print "\r" end
else

# Append the input to whatever we had.
expr << line

# Determine changes in indentation, reposition this line if
# necessary, and adjust indentation for the next prompt.
begin
ind1,ind2 = indentation( line )
if( ind1 != 0 )
indent += ind1
print Wipe,PrMore,(Ispace*indent),Code,line,Norm
end
indent += ind2
rescue # On error, restart the main loop.
print Eval,"ERR: Nesting violation\n",Norm
indent = 0
redo
end

# Okay, do we have something worth evaulating?
if (indent == 0) && (expr.chop =~ /[^; \t\n\r\f]+/)
begin
result = eval(expr, TOPLEVEL_BINDING).inspect
if $! # no exception, but $! non-nil, means a warning
print Eval,$!,Norm,"\n"
$!=nil
end
print Eval," ",result,Norm,"\n"
rescue ScriptError,StandardError
$! = 'exception raised' if not $!
print Eval,"ERR: ",$!,Norm,"\n"
end
break if not line
end
end
end # Bottom of main loop
print "\n"

end


10 changes: 10 additions & 0 deletions bin/example.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class Klass
attr_accessor :str
end
s1 = Klass.new #=> #<Klass:0x401b3a38>
s1.str = "Hello" #=> "Hello"
s2 = s1.clone #=> #<Klass:0x401b3998 @str="Hello">
s2.str[1,4] = "i" #=> "i"
s1.inspect #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
s2.inspect #=> "#<Klass:0x401b3998 @str=\"Hi\">"

40 changes: 40 additions & 0 deletions bin/regx.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Requires an ANSI terminal!

st = "\033[7m"
en = "\033[m"

puts "all moms and dads r worring - might it be that our own san is really a gay ?"



#while true
# print "str> "; STDOUT.flush; str = gets.chop
# break if str.empty?
# print "pat> "; STDOUT.flush; pat = gets.chop
# break if pat.empty?

#"i'm not gay"





re = Regexp.new("f.*z")
# ("/[i][gay]/")
# str = "i already told you: I'm not gay!"
#
str = "foozbooze"
puts str.gsub(re,"#{st}\\&#{en}")

re = Regexp.new("i..gay")

# "[i][am][not][gay]")
# ("/[i][gay]/")
# str = "i already told you: I'm not gay!"
#
str = "i am not gay"
#end


puts str.gsub(re,"#{st}\\&#{en}")

28 changes: 28 additions & 0 deletions bin/rescue.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
begin
foo
rescue Exception => e
# ...
end
message = ""
users.each do |user|
user.activated = true
unless user.save
message += "#{user.name}: " +
"#{user.errors.full_messages.join('; ')}"
end
end
unless message.blank?
flash[:warning] = "Unable to update some " +
"of the users: #{message}"
end
begin
my_unpredicable_method(params)
rescue => e
HoptoadNotifier.notify(
:error_class
=> "Special Error",
:error_message => "Special Error: #{e.message}"
)
end


171 changes: 171 additions & 0 deletions bin/variables.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
#! /usr/bin/env ruby
puts "\n\nhow not to get sex ? - guide to rubyiest \n\n"




class Woman
@@want_sex= false
@want_sex = false
@kind = 'Woman'

def initialize(want)
puts 'initialize..'
@want_sex = false || want
end

def self.want_sex
#$puts self.Class
puts 'kind: ' + kinda()
#puts 'answer:' + @@want_sex_static_boolean.to_s
puts 'answer: ' + @@want_sex.to_s
puts
puts

end
def self.kinda
return 'kind is is: ' + @kind
end
end

puts Woman.want_sex


class Hooker < Woman


attr_accessor :money
def initialize()

end

@kind = 'Hooker'
def self.want_sex #oppoiste from Woman
@@want_sex = !@@want_sex
super
end
end

puts Hooker.want_sex

class Smart_Hooker < Hooker
@kind = 'Smart_Hooker'
def self.want_sex_for_money(moneyy=0) #no change to the static var
if(moneyy > 0)
#
self.superclass.superclass.want_sex #show @kind of
else
# super
puts 'how much money u\'ve got ?'

end
end
end
puts Smart_Hooker.want_sex_for_money(10)


#class Invastigative_Hooker < Hooker
#def self.want_sex
#def initialize
#if(money > 0)
#!super
#else
#puts 'how old r u ?, i could be your mother! - get off!'
#end

#end

#end
#end
puts
puts
puts 'class vars: ' + Woman.class_variables.to_s # => @@sides
puts 'instance vars: ' + Woman.instance_variables.to_s # => @sides



def deep_copy

puts 'horney guy: lets c how smart they r today !'
h1 = Hooker.new #=> #<Klass:0x401b3a38>
h1.money = 100

puts "horney guy: how much do u take miss 1 ?"

puts "hooker1: for u #{h1.money}"

puts "our guy corssing the road to another hooker "

puts "horney guy: how much do u take miss 2 ?"

h2 = h1.clone #=> #<Klass:0x401b3998 @str="Hello">
h2.money = h2.money - 10

puts "hooker2: for u its #{h2.money}"
puts "horney guy: its a deal!"
puts "hooker1: hey! you! come over here - for u its only #{h1.money} "
puts 'extra info:'
h1.inspect

h2.inspect
#puts 'explain: '
end








deep_copy()
#but shallow copy for strings:
class Klass
attr_accessor :str
end
s1 = Klass.new #=> #<Klass:0x401b3a38>
s1.str = "Hello" #=> "Hello"
s2 = s1.clone #=> #<Klass:0x401b3998 @str="Hello">
s2.str[1,4] = "i" #=> "i"
s1.inspect #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
s2.inspect #=> "#<Klass:0x401b3998 @str=\"Hi\">"




#Adds to obj the instance methods from each module given as a parameter.

module Mod
def hello
"Hello from Mod.\n"
end
end

class Klass
def hello
"Hello from Klass.\n"
end
end

k = Klass.new
k.hello #=> "Hello from Klass.\n"
k.extend(Mod) #=> #<Klass:0x401b3bc8>
k.hello #=> "Hello from Mod.\n"




def getBinding(param)
puts 'new params:'+ param.to_s
return binding
end
b0 = getBinding("hello")
b0.eval("param") #=> "hello"

puts '--'
b1 = getBinding("3+3")
b1.eval("param") #=> "hello"
puts '--'
b2 = getBinding(3+3)
b2.eval("param") #=> "hello"

0 comments on commit 3b71379

Please sign in to comment.