Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #it's getting really hard :o
- #read and write a file with and without blocks
- #method with blocks
- filename = 'text.txt'
- #write
- File.open(filename,'w') {|file| file.write('ola ate logo')}
- #read
- File.open(filename,'r') {|file| puts file.read}
- #method without blocks
- filename = 'text.txt'
- #write
- file = File.open(filename,'w')
- file.write('ola')
- file.close
- #read
- file = File.open(filename,'r')
- puts file.read
- file.close
- #can I translate hash to array? And array to hash?
- #hash to array
- array = []
- hash = { "a"=>["a", "b", "c"], "b"=>["b", "c"] }
- hash.each_key {|p| array.push(hash[p])}
- #array to hash
- array = [["a", "b", "c"], ["b", "c"]]
- hash = Hash[*array]
- #can I iterate through a hash ?
- hash.each_value {|p| puts "-> #{p}"}
- ##DO
- #Exercise 1
- #
- a = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16']
- #
- a.each {|p| puts "-> #{p}"}
- #
- a.each_slice(4) {|p| puts "-> #{p}"}
- #Exercise 2
- #Well, it's a little more complicated, so I need to make an example first and then implement in the tree
- #So, based on this
- hs = {"grandpa" => {"dad" => {"child1" => {}, "child2" => {}}, "uncle" => {"child3" => {}, "child4" => {}}}}
- def readAll(tree = {})
- puts "tree-> #{tree}"
- nome = tree.keys[0]
- child = tree[nome].collect {|i,m| readAll(i=>m)}
- end
- readAll(hs)
- #I updated the tree
- class Tree
- attr_accessor :children, :node_name
- def initialize(tree={})
- @node_name = tree.keys[0]
- @children = tree[node_name].collect {|i,m| Tree.new(i=>m)}
- 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( {"grandpa" => {"dad" => {"child1" => {}, "child2" => {}}, "uncle" => {"child3" => {}, "child4" => {}}}} )
- puts "visiting entire tree"
- ruby_tree.visit_all {|node| puts node.node_name}
- #Exercise 3
- #the file text.txt contains
- ola ate logo
- ja sei
- ainda nao sei
- #and the code is
- File.open('text.txt','r').each_with_index {|l,p| puts "-> #{l},#{p}" if l=~/sei(.*)/ }
- #you can also use readlines or each_line insted of each_with_index but you will not get the index of line
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement