在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1#!/usr/bin/env ruby
2 3class MegaGreeter 4 attr_accessor :names //设置属性,自动产生两个方法(name,name=)用来访问@name的值 //想知道一个类提供了那些方法?类名.instance_methods会告诉你,如果只想知道自己定义的方法加个false参数 5 6 # Create the object 7 def initialize(names = "World") //构造函数 8 @names = names //定义了局部变量@names 9 end 10 11 # Say hi to everybody 12 def say_hi 13 if @names.nil? //判断@names是否为nil 14 puts "" //输出 15 elsif @names.respond_to?("each") //判断@names是否有each方法 16 17 # @names is a list of some kind, iterate! 18 @names.each do |name| //循环 19 puts "Hello #{name}!" 20 end 21 else 22 puts "Hello #{@names}!" 23 end 24 end 25 26 # Say bye to everybody 27 def say_bye 28 if @names.nil? 29 puts "" 30 elsif @names.respond_to?("join") 31 # Join the list elements with commas 32 puts "Goodbye #{@names.join(", ")}. Come back soon!" 33 else 34 puts "Goodbye #{@names}. Come back soon!" 35 end 36 end 37 38end 39 40 41if __FILE__ == $0 //__FILE__ 现在运行的脚本文件的名字, $0 是启动脚本的名字.//这允许代码作为库调用的时候不运行启动代码, 而在作为执行脚本的时候调用启动代码。 42 mg = MegaGreeter.new 43 mg.say_hi 44 mg.say_bye 45 46 # Change name to be "Zeke" 47 mg.names = "Zeke" 48 mg.say_hi 49 mg.say_bye 50 51 # Change the name to an array of names 52 mg.names = ["Albert", "Brenda", "Charles", 53 "Dave", "Englebert"] 54 mg.say_hi 55 mg.say_bye 56 57 # Change to nil 58 mg.names = nil 59 mg.say_hi 60 mg.say_bye 61end |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论