美文网首页
Ruby 方法

Ruby 方法

作者: changsanjiang | 来源:发表于2017-09-23 20:07 被阅读5次

#!/usr/bin/ruby
# -*- coding:UTF-8 -*-

# 方法
    # 方法名应以小写字母开头. 如果以大写字母开头, Ruby 可能会把它当作常量.
    # 方法应在调用之前定义, 否则 Ruby 会报出未定义的方法调用异常.

# 不带参数的方法
def method1
    puts "Hello Ruby"
end

# 带参数的方法
    # 使用带参数方法最大的缺点是调用方法时需要记住参数个数. 如果参数个数不对, Ruby 会报错. 
def method2(name, age)
    puts name, age
end

# 方法的返回值
    # Ruby 中每个方法默认返回最后一个语句的值.
def max_method(num1, num2)
    num1 > num2 ? num1 : num2
end

# return 语句
    # return 语句用与从 Ruby 方法中返回一个或多个值.
    # return 或
    # return 1 或
    # return 1, 2, 3
def return_method
    i = 100
    j = 200
    k = 300
    return i, j, k 
end


# 可变数量的参数
def mutable_parameters_method(*test)
    puts "参数个数为 #{test.length}"
    for i in 0 ... test.length
        puts "第 #{i} 个参数 = #{test[i]}"
    end
end


# 类方法
    # 方法定义在类的外部, 方法默认标记为 private.
    # 方法定义在类中的, 则默认标记为 public.
    # 方法默认的可见性和 private 标记, 可通过模块的 public 或 private 改变. 
    # 当你想要访问类的方法时, 您首先需要实力化类. 
class Class1
        def test
        end
       # Ruby 提供了一种不用实例化即可访问方法的方式. 声明如下.
    def Class1.class_method
        puts "call class method"
    end
end


# alias 语句
    # 这个语句用于为方法或全局变量起别名. 
    # 别名不能在方法主体内定义.
    # 即使方法被重写, 方法的别名也保持方法的当前定义. 
alias alias_method1 method1
 



# undef 语句
    # 这个语句用于取消方法定义. undef 不能出现在方法主体内.
    # 通过 undef 和 alias, 类的接口可以从父类独立修改.
    # 但请注意, 在自身内部方法调用时, 它可能会破坏程序. 

undef alias_method1


method1
method2("xiaoMing", 12)
puts max_method(6, 2)
puts return_method

mutable_parameters_method(-1, 0, 1, 2, 3, 4)

Class1.class_method

puts "别名 #{alias_method1}"

相关文章

  • From Objective-C to Ruby(4)-类和模块

    类 定义类 OC: ruby: 初始化方法 OC: ruby: 实例变量和属性 OC: ruby: 类方法和对象方...

  • From Objective-C to Ruby(3)-方法和块

    方法 定义方法 OC: ruby: 调用方法 OC: ruby: 参数的默认值 OC: 方法的返回值 OC: ru...

  • 器-用:ruby高效能方法 — reduce方法

    一、reduce方法的作用 reduce方法是ruby中的一个重要的方法,也叫inject方法(Ruby1.9之前...

  • ruby 数据类型

    1. Ruby 字符串(String) 2. Ruby 数组 3. Ruby 哈希 哈希的内置方法 4. Ruby...

  • Ruby、RVM-使用总结

    Ruby、RVM-使用总结 安装或更新Ruby 方法一:使用Homebrew安装Ruby Homebrew 是什么...

  • Ruby方法

    Ruby 方法与其他编程语言中的函数类似。Ruby 方法用于捆绑一个或多个重复的语句到一个单元中。方法名应以小写字...

  • Ruby 方法

  • Ruby 方法

    Ruby 方法用于捆绑一个或多个重复的语句到一个单元中。方法名应以小写字母开头。如果您以大写字母作为方法名的开头,...

  • 常用的Ruby方法

    1 当你发送消息到Ruby对象时,Ruby查询与消息同名的方法来调用。Ruby进行方法调用主要有两种方式,obj...

  • OS X上部署Ruby on Rails环境问题

    部署方法照 https://ruby-china.org/wiki/install_ruby_guide 进行,但...

网友评论

      本文标题:Ruby 方法

      本文链接:https://www.haomeiwen.com/subject/cefhextx.html