Ruby初体验——第一个小程序sort

是学校的课程作业

要求掌握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里面编写和运行的

环境配置很简单

有兴趣的也可以自己尝试一下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值