Skip to content

Instantly share code, notes, and snippets.

@8bit-pixies
Last active October 13, 2015 19:18
Show Gist options
  • Save 8bit-pixies/4243257 to your computer and use it in GitHub Desktop.
Save 8bit-pixies/4243257 to your computer and use it in GitHub Desktop.
Seven Languages in Seven Weeks - Ruby Day 1 Day 2
#day1 questions
puts "Hello, world"
puts "Hello, Ruby".index("Ruby")
x=0
while x < 10
puts "Chapman"
x = x + 1
end
def guess_rank
x=rand(10)
print "Guess number between 0-9: "
guess = x+1
while x!=guess
guess = gets.to_i
puts "lower" if x<guess
puts "higher" if x>guess
puts "correct" if x==guess
end
end
guess_rank
array = [*(1..16)]
#print the arrays 4 at a time
#array.each {|num| 4.times{puts num}}
array.each {|num| puts array[((num-4)..num)] if num % 4 ==0}
array.each_slice(4) {|num| puts num}
class Tree
attr_accessor :children, :node_name
def initialize(name,children = [])
#make it accept hash keys use .respond_to?('keys')
#to check for this
if name.respond_to?('keys') then
#get first layer of the list
root_node = name.first
name = root_node[0]
children = root_node[1]
end
#subsequent layers
if children.respond_to?('keys') then
children = children.map {|child,grandchildren| Tree.new(child,grandchildren)}
end
@children = children
@node_name = name
end
def visit_all(&block)
visit &block
children.each {|c| c.visit_all &block}
end
def visit(&block)
block.call self
end
end
#have a sample text
files = File.open('text.txt','w+')
files.puts "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
files.puts "Maecenas viverra condimentum augue a pulvinar. "
files.puts "Etiam vitae nibh nibh, ut dignissim ligula. "
files.puts "Morbi vehicula tellus eu nunc consequat gravida. "
files.puts "Proin mattis velit sit amet metus dapibus venenatis. "
files.puts "Nunc auctor vulputate justo, imperdiet euismod urna pharetra vitae. "
files.puts "Aenean feugiat eleifend purus eget fermentum. "
files.puts "Donec fringilla imperdiet turpis non feugiat. "
files.close
#to use grep to find the text, use the perl like syntax =~
def grepping(pattern)
File.open('text.txt','r').each {|line| puts "#{line}" if Regexp.new(pattern) =~ line }
end
grepping('vitae')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment