What is a more "ruby way" to write this code?
Posted
by steadfastbuck
on Stack Overflow
See other posts from Stack Overflow
or by steadfastbuck
Published on 2010-06-15T06:37:16Z
Indexed on
2010/06/15
6:42 UTC
Read the original article
Hit count: 159
ruby
|coding-style
This was a homework assignment for my students (I am a teaching assistant) in c and I am trying to learn Ruby, so I thought I would code it up. The goal is to read integers from a redirected file and print some simple information. The first line in the file is the number of elements, and then each integer resides on its own line.
This code works (although perhaps inefficiently), but how can I make the code more Ruby-like?
#!/usr/bin/ruby -w
# first line is number of inputs (Don't need it)
num_inputs = STDIN.gets.to_i
# read inputs as ints
h = Hash.new
STDIN.each do |n|
n = n.to_i
h[n] = 1 unless h[n] and h[n] += 1
end
# find smallest mode
h.sort.each do |k,v|
break puts "Mode is: #{k}", "\n" if v == h.values.max
end
# mode unique?
v = h.values.sort
print "Mode is unique: "
puts v.pop == v.pop, "\n"
# print number of singleton odds,
# odd elems repeated odd number times in desc order
# even singletons in desc order
odd_once = 0
odd = Array.new
even = Array.new
h.each_pair do |k, v|
odd_once += 1 if v == 1 and k.odd?
odd << k if v.odd?
even << k if v == 1 and k.even?
end
puts "Number of elements with an odd value that appear only once: #{odd_once}", "\n"
puts "Elements repeated an odd number of times:"
puts odd.sort.reverse, "\n"
puts "Elements with an even value that appear exactly once:"
puts even.sort.reverse, "\n"
# print fib numbers in the hash
class Fixnum
def is_fib?
l, h = 0, 1
while h <= self
return true if h == self
l, h = h, l+h
end
end
end
puts "Fibonacci numbers:"
h.keys.sort.each do |n|
puts n if n.is_fib?
end
© Stack Overflow or respective owner