Skip to content

Instantly share code, notes, and snippets.

@rkjha
Last active December 18, 2015 00:09
Show Gist options
  • Save rkjha/5694490 to your computer and use it in GitHub Desktop.
Save rkjha/5694490 to your computer and use it in GitHub Desktop.
First ruby program reads a file containing numbers (separated by space), and calculates the each occurrence of the number (a.k.a frequency distribution). Second one, simply prints a number from 1 to n with the condition (if it's divisible by 3 then Hip, divisible by 5, then Hop, and if it's divisible by both 3 and 5, then it prints Whazaa)
# assuming the file is there in the same dir as numbers.txt
file = File.open("numbers.txt", 'r')
frequency_db = Hash.new
file.each_line do |line|
line_n = line.split
line_n.each do |n|
if frequency_db.has_key?(n)
frequency_db[n]+=1
else
frequency_db.store(n,1)
end
end
end
#now displays the frequency distribution
frequency_db.each do |number, frequency|
puts "#{number}: #{frequency}"
end
def take_n n
number = n.to_i
i=1
while i<= number do
if i%3 == 0
if i%5 == 0
puts "Whazaa"
else
puts "Hip"
end
elsif i%5 ==0
puts "Hop"
else
puts i
end
i = i+1
end
end
# get first number as the input (e.g ruby file_name.rb 20)
take_n ARGV[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment