[ create a new paste ] login | about

Link: http://codepad.org/EMbqAWNO    [ raw code | output | fork | 1 comment ]

joshua_cheek - Ruby, pasted on Oct 26:
#Learning Ruby chapter 1
puts "VERSION = #{VERSION}"

#appending a string
puts "1Hello " + "world"
puts "2Hello " << "world"

#repetition of strings
puts "3Hello world!! " * 3
3.times{ print "4Hello World!" }

#inserting shell command
#actual is commented, b/c codepad does not like me running shell commands on their server
puts "\n5Hi world, I'm running " #+ `ruby --version`  

#variable
hi = "6Hello "
person = "7world"
puts hi , hi+person

#expression substitution
puts "8Hello #{person}"
puts "9Hello #{ARGV[0]}" #won't show up if run w/o command line input
hi = "10Hello %s, how are you?"
puts hi % "world"
puts "11%s, %s, how are you?" % ["Hello","world"]
a = sprintf( "%dHello %s, how are you?" , 12 , "world" )
puts a

#input
#print "who do you want to say hello to? "
#gets person
#puts "13Hello, #{person}"

#method
def hello
  puts "14Hello world"
end
hello

#yielding, places the block where the code is
def hello(number)
  puts "#{number}pre"
  yield
  puts "#{number}post"
end
hello(15){ puts "15hello, world" }

#iteration of array
[16 , "Hello, " , "world"].each{ |i| print i }
puts

#procs (procedures)
prc = lambda{ |number,name| puts "#{number}Hello, " + name }
prc.call(17,"world")

#XMP and files
#commented b/c codepad does not like me creating files on their server
#require "rexml/document"
#file = File.new( "world.xml" ) 
#doc = REXML::Document.new file
#puts 18.to_s + doc.to_s

#classes
class Hello
  def initialize( name )
    @name = name
  end
  
  def hello_whoever(number)
    puts "#{number}Hello, " + @name + "!"
  end
end

hi = Hello.new( "world" )
hi.hello_whoever(19)

#an uncaught exception
throw "oops"  


Output:
Line 79:in `throw': uncaught throw `oops' (NameError)
	from t.rb:79
VERSION = 1.8.6
1Hello world
2Hello world
3Hello world!! 3Hello world!! 3Hello world!! 
4Hello World!4Hello World!4Hello World!
5Hi world, I'm running 
6Hello 
6Hello 7world
8Hello 7world
9Hello 
10Hello world, how are you?
11Hello, world, how are you?
12Hello world, how are you?
14Hello world
15pre
15hello, world
15post
16Hello, world
17Hello, world
19Hello, world!


Create a new paste based on this one


Comments:
posted by joshua_cheek on Nov 15
My notes from when I read Learning Ruby
(I didn't expect anyone else to look at them, but a friend asked for info on Ruby)
reply