ruby.new

1873 ワード

ruby.new


出力:print、puts、p


コメント

#say hello
=begin
this is a long comment
=end

変数#ヘンスウ#

local: time or _time
instance: @time
class: @@time
global $time

データ型

Numeric
String
Symbol
Boolean
Array
Hash

方法

def plus(x,y)
    z = x + y
    return z
end
plus(3,4)
def plus x,y
    x + y
end
plus 3,4
  • overridingのみoverloading
  • なし

    block

    def hello
            yield
    end
    hello {puts "hello, block"}
    [1,2,3,4,5].each{|i| puts i}
    [1,2,3,4,5].each_with_index{|i, index| puts i, index}
    [1,2,3,4,5].map{|i| i**2 }
    [1,2,3,4,5].select{|i| i%2==0 }
    [1,2,3,4,5].reject{|i| i%2==0 }
    [1,2,3,4,5].inject{|sum, i| sum += i}

    LambdaとProc


    class

    class Bird
      attr_accessor :name, :sex
      attr_reader :age
      attr_writer :hometown
      def initialize name
        @name = name
      end
      
      def self.fly
        puts "bird can fly"
      end
      
      def say
        puts "i am #{@name}"
      end
    end
    
    bird = Bird.new("didi")
    bird.sex = "male"
    Bird.fly
    class LittleBird < Bird
      def initialize name
        super(name)
      end
    end

    module

  • rubyにはinterfaceはありませんが、moduleとmixinメカニズムがあります.
  • module Eat
      def eat
        p "i can eat"
      end
    end
    
    module Sleep
      def sleep
        p "i can sleep"
      end
    end
    
    class Pig
      include Eat
      include Sleep
    end
    
    Pig.new.eat
    Pig.new.sleep
    module Math 
        PI = 3.14
    end
    
    Math::PI

    code


    r1.rb