是学校的课程作业
要求掌握Ruby的简单使用
所以代码没有实际意义
只是拿来熟悉Ruby代码的语法和结构等
下面贴上代码供大家参考
module Output
def print_hush(a)
a.each do | item, price |
puts "#{item} => #{price}"
end
end
def print_array(b)
length = b.length
length.times do |t|
print "#{b[t]} "
end
puts "\n"
end
def print_string(c)
puts c
end
end
class Sort
include Output
def array_sort(a)
return a.sort {|x,y| x <=> y }
end
def hush_sort(x)
return x.sort {|a,b| a[1]<=>b[1]}
end
def string_sort(x)
y = x.split("*")
return y.sort { |a,b| a.length<=>b.length }
end
end
END{
puts "\nBefore sort(array):"
p b1 = ((1..100).to_a + (20..80).to_a).shuffle.sample(10)
s1 = Sort.new
puts "Sorted:"
s1.print_array(s1.array_sort(b1))
}
puts "\nBefore sort(hush):"
b2 = {:oneone =>5,:twotwo =>10,:threethree =>2,:fourfour =>8, :fivefive =>50}
puts b2
s2 = Sort.new
puts "Sorted:"
s2.print_hush(s2.hush_sort(b2))
puts "\nBefore sort(string):"
def gen_rand_str(len)
rand_indexes = (0...len).collect{|i| rand(62)}
[*('a'..'z'),*('A'..'Z')].values_at(*rand_indexes).join
end
a15=gen_rand_str(15)
a8=gen_rand_str(8)
a12=gen_rand_str(12)
b3 = a15 +'*'+ a8 +'*' + a12
puts a15 +"\n"+ a8 + "\n" + a12
s3 = Sort.new
puts "Sorted:"
s3.print_string(s3.string_sort(b3))
代码是在vs code里面编写和运行的
环境配置很简单
有兴趣的也可以自己尝试一下