Skip to content

Instantly share code, notes, and snippets.

@jomontanari
Created October 28, 2011 16:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jomontanari/1322655 to your computer and use it in GitHub Desktop.
Save jomontanari/1322655 to your computer and use it in GitHub Desktop.
Ruby - Day 2
# With block - closes file automatically
File.open("test.txt") do |file|
puts file.readlines
end
# Without block
file = File.open("test.txt")
puts file.readlines
file.close
# Convert hash to array
my_hash = {:jo => "developer", :barry => "pm", :brett => "ba", :david => "developer"}
my_array = my_hash.to_a
# Convert array to hash
my_nested_array = [[:jo, "developer"], [:barry, "pm"], [:brett, "ba"], [:david, "developer"]]
hash_from_nested_array = Hash[my_nested_array]
hash_from_flat_array = Hash["jo", "developer", "barry", "pm"]
puts "Which file should I look at?"
file_name = gets().strip
puts "Enter a phrase to search for?"
phrase = gets().strip
regex = Regexp.new(phrase)
File.open(file_name) do |file|
linenum = 0
matches = 0
file.readlines().each do |line|
linenum+=1
unless regex.match(line).nil?
puts "#{phrase} is contained in line #{linenum}: #{line}"
matches+=1
end
end
puts "Total matches: #{matches}"
end
my_hash = { "a" => 1, "b" => 2}
my_hash.each {|key,val| puts "#{key} has a value of #{val}"}
my_hash.each_pair {|key,val| puts "#{key} has a value of #{val}"}
my_hash.each_key { |key| puts "#{key} has a value of #{my_hash.fetch(key)}" }
my_hash.each_value {|val| puts "Hash contains value #{val}"}
sixteen_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
# yuck. really do not like this solution with 'each'
puts "Next 4"
sixteen_numbers.each do |num|
print num if (1..4).include?(num)
end
puts
puts "Next 4"
sixteen_numbers.each do |num|
print num if (5..8).include?(num)
end
puts
puts "Next 4"
sixteen_numbers.each do |num|
print num if (9..12).include?(num)
end
puts
puts "Next 4"
sixteen_numbers.each do |num|
print num if (13..16).include?(num)
end
puts
puts "each_slice method"
sixteen_numbers.each_slice(4) {|nums| puts "Next 4: #{nums}"}
class Tree
attr_accessor :children, :node_name
def initialize(name, treedef)
@node_name = name
@children = []
treedef.each { |key,val| @children << Tree.new(key, val)}
end
def visit_all(&block)
visit &block
@children.each {|c| c.visit_all &block}
end
def visit(&block)
block.call self
end
end
#ruby_tree = Tree.new("Ruby", [Tree.new("Reia"), Tree.new("MacRuby")])
family_tree = Tree.new("Family", {'grandpa' => {'dad' => {'child 1'=> {}, 'child 2' => {}}, 'uncle' => {'child 3' => {}, 'child 4' => {}}}})
puts "Visiting a node"
family_tree.visit { |node| puts node.node_name}
puts
puts "Visiting entire tree"
family_tree.visit_all {|node| puts node.node_name}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment