ruby入门首次作业

1、每行5个数字,用逗号分隔,每行最后一个数字不用逗号。


def foo(n)
    if n.instance_of?(Fixnum) then
      for i in 1..n
            print i
            if(i%5!=0 && i!=n) then
                print ","
            end
            if(i%5==0 || i==n) then
                print "\n"
            end
      end
    else
      puts "请输入整形参数。"    
    end
end


foo(3)
foo(9)
foo(21)
foo("test")

2、乘法表(不论什么语言入门都必须的东西)

def multiplicationtable(n)
    for i in 1..n
        for j in 1..i
          mul = i*j
          print  i.to_s+"*"+j.to_s+"="+mul.to_s
          print "   "
        end
          print "\n"
    end
end

multiplicationtable(10)



3、按指定格式输出一周的日期和星期。(周日到周六)

def week(t)
    sec=60*60*24
    for i in 0..6
        print (t+(i-t.wday)*sec).strftime("%m/%d (%a)") + "\n"
    end
end
t=Time.now
week(t)

4、语法纠错题(下面是正确的),主要为了熟悉类变量的初始化、区分类方法和实例方法

class Robot
	@@count = 0 #初始化
   def ping  #实例方法
     @@count +=1
   end

   def self.count #类方法
     @@count
   end
end
r1 = Robot.new
r1.ping
r2 =Robot.new
r2.ping
r1.ping
puts Robot.count

5、文本读取,分割并格式化输出

f=File.new("hashdata.txt")
while !f.eof()
        a= f.readline().split("        ")
        lineno=(f.lineno).to_s
        print lineno+":"+a[0]+"->"+a[1]
end

简单总结一下,instance_of?判断输入值的类型,t.wday获取日期为本周的第几天,f.lineno和f.eof分别为行号和判断文件读取是否已完成。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值