Skip to content

Instantly share code, notes, and snippets.

@jlgeering
Created July 28, 2011 06:36
Show Gist options
  • Save jlgeering/1111089 to your computer and use it in GitHub Desktop.
Save jlgeering/1111089 to your computer and use it in GitHub Desktop.
Seven Languages in Seven Weeks: Ruby
a = [1,3,5] # => [1, 3, 5]
s = "hello world"
s.sub("world", "john") # => "hello john"
ENV['SHELL'] # => "/bin/bash"
def ex1
puts "Hello World!"
end
def ex2
'Hello Ruby' =~ /Ruby/
end
ex2 # => 6
def ex3
10.times { puts "JLG" }
end
def ex4
(1..10).each { |e| puts "this is sentence number #{e}" }
end
def ex6
r = rand(10)
guess = -1
until guess == r
puts "type a number between 0 and 9 (or anything else to quit)"
guess = gets.chomp
puts case guess
when /[0-9]/
guess = guess.to_i
case
when guess < r
'too low'
when guess > r
'too high'
else
'well done'
end
else
guess = r
'bye'
end
end
end
# Global variables begin with $. Uninitialized global variables have the value nil and produce warnings with the -w option.
$filename = 'test.txt'
#########
# Files #
#########
def read_the_entire_contents_of_a_file_without_using_a_block
file = File.open($filename, 'r')
file.each_line { |line| puts line }
file.close
end
# The advantage of using it in a block is that Ruby will ensure the file is closed
def read_the_entire_contents_of_a_file_in_a_block
contents = File.open($filename, 'r') { |file| file.read }
# puts contents
lines = []
File.open($filename, 'r') do |file|
file.each_line do |line|
lines << line
end
end
# puts lines
# using IO
lines = []
IO.foreach($filename) { |line|
lines << line
}
# or returning an array
lines = IO.readlines($filename, '.')
end
def write_to_file
File.open("out.txt", "w") { |file|
file << "Foo"
file << "Bar"
}
end
##########
# Hashes #
##########
# hash to array
h = { "c" => 300, "a" => 100, "d" => 400, "c" => 200 }
h # => {"a"=>100, "c"=>200, "d"=>400}
h.to_a # => [["a", 100], ["c", 200], ["d", 400]]
h.to_a.flatten # => ["a", 100, "c", 200, "d", 400]
c = h.collect { |key, value| "#{key} => #{value}" }
c # => ["a => 100", "c => 200", "d => 400"]
c = h.collect { |key, value| [key,value] }
c # => [["a", 100], ["c", 200], ["d", 400]]
c.flatten(1) # => ["a", 100, "c", 200, "d", 400]
a = [1,2,3,4]
[a] # => [[1, 2, 3, 4]]
(1..6) # => 1..6
[(1..6)] # => [1..6]
# could not find documentation for this operator / notation !
[*a] # => [1, 2, 3, 4]
[*c] # => [["a", 100], ["c", 200], ["d", 400]]
[*c.flatten(1)] # => ["a", 100, "c", 200, "d", 400]
[*(1..6)] # => [1, 2, 3, 4, 5, 6]
# Array to Hash
Hash[a] # => {}
Hash[*a] # => {1=>2, 3=>4}
Hash[c] # => {"a"=>100, "c"=>200, "d"=>400}
Hash[*c.flatten(1)] # => {"a"=>100, "c"=>200, "d"=>400}
# EX 1
def iterate_with_each(numbers)
buf = []
numbers.each do |n|
# buf.push n
buf << n
if buf.length == 4 then
puts buf.inspect
buf = []
end
end
if buf.length then
puts buf.inspect
buf = []
end
end
def iterate_with_each_slice(numbers)
numbers.each_slice(3) {|a| p a}
end
numbers = [*(1..15)] # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
#iterate_with_each(numbers)
#iterate_with_each_slice(numbers)
# EX 2
class Tree
attr_accessor :children, :node_name
# 1 arg constructor
#def initialize(a)
# if a.is_a? Hash and a.length == 1 then
# tuple = a.first
# @node_name = tuple[0]
# @children = tuple[1].collect { |key,value| Tree.new({key, value}) }
# else
# raise ArgumentError
# end
#end
def initialize(a, b = nil)
if a.is_a? String and b.is_a? Hash then
@node_name = a
@children = b.collect { |key,value| Tree.new(key, value) }
elsif a.is_a? Hash and b.nil? and a.length == 1 then
tuple = a.first
@node_name = tuple[0]
@children = tuple[1].collect { |key,value| Tree.new(key, value) }
else
raise ArgumentError
end
end
def to_tuple
children_hash = Hash[@children.collect { |t| t.to_tuple }]
[ @node_name, children_hash ]
end
def to_hash
# Hash[[self.to_tuple]]
Hash[*self.to_tuple]
end
end
baby_t = Tree.new("a", {})
baby_t.to_tuple # => ["a", {}]
baby_t.to_hash # => {"a"=>{}}
big_t = Tree.new({"a" => {"a1" => {"a11" => {}, "a12" => {"a121" => {}}}, "a2" => {}, "a3" => {"a31" => {}, "a32" => {}, "a33" => {}}}})
big_t.to_tuple # => ["a", {"a1"=>{"a11"=>{}, "a12"=>{"a121"=>{}}}, "a2"=>{}, "a3"=>{"a32"=>{}, "a33"=>{}, "a31"=>{}}}]
big_t.to_hash # => {"a"=>{"a1"=>{"a11"=>{}, "a12"=>{"a121"=>{}}}, "a2"=>{}, "a3"=>{"a32"=>{}, "a33"=>{}, "a31"=>{}}}}
# EX 3
def my_grep(re, filename)
# without line numbers
# matches = []
# IO.foreach(filename) { |line|
# matches << line.chomp if line =~ re
# }
# with line numbers
matches = {}
IO.foreach(filename).each_with_index { |line, i|
# first line has index 0
matches[i+1] = line.chomp if line =~ re
}
matches
end
matches = my_grep(/ir.t/, $filename) # => {1=>"this is the first line"}
#!/usr/bin/env ruby
filename = ARGV[0]
re = ARGV[1]
if (filename.nil? || re.nil?)
puts "Usage: ./grep.rb filename regexp"
exit;
end
File.open(filename, File::RDONLY) do |file|
file.each_with_index { |line, nr| puts "Line #{(nr+1).to_s.rjust(3)}: #{line}" if line =~ Regexp.new(re) }
end
this is the first line
this is the second line
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment