码迷,mamicode.com
首页 > 其他好文 > 详细

20分钟ruby

时间:2016-07-23 19:44:55      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

ref:https://www.ruby-lang.org/en/documentation/quickstart/

#!/usr/bin/env ruby

class MegaGreeter
  attr_accessor :names

  # Create the object
  def initialize(names = "World")
    @names = names
  end

  # Say hi to everybody
  def say_hi
    if @names.nil?
      puts "..."
    elsif @names.respond_to?("each")
      # @names is a list of some kind, iterate!
      @names.each do |name|
        puts "Hello #{name}!"
      end
    else
      puts "Hello #{@names}!"
    end
  end

  # Say bye to everybody
  def say_bye
    if @names.nil?
      puts "..."
    elsif @names.respond_to?("join")
      # Join the list elements with commas
      puts "Goodbye #{@names.join(", ")}.  Come back soon!"
    else
      puts "Goodbye #{@names}.  Come back soon!"
    end
  end
end


if __FILE__ == $0
  mg = MegaGreeter.new
  mg.say_hi
  mg.say_bye

  # Change name to be "Zeke"
  mg.names = "Zeke"
  mg.say_hi
  mg.say_bye

  # Change the name to an array of names
  mg.names = ["Albert", "Brenda", "Charles",
              "Dave", "Engelbert"]
  mg.say_hi
  mg.say_bye

  # Change to nil
  mg.names = nil
  mg.say_hi
  mg.say_bye
end

 1. attr_accseeor  :name

  使 MegaGreeter.instance_methods false 的返回值(Array)多了  :id :id= 两项

      mg.respond_to? :id   或  mg.respond_to?("id")    

      mg.respond_to? :id=  或 mg.respond_to?("id=")    为true

2. 使用对象的属性而非对象的类型决定执行方式

    @names.respond_to?

3.   __FILE__==$0

  

   

20分钟ruby

标签:

原文地址:http://www.cnblogs.com/Citizen/p/5699328.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!