符号如何用于识别ruby方法中的参数 [英] How are symbols used to identify arguments in ruby methods

查看:96
本文介绍了符号如何用于识别ruby方法中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Rails,然后回到ruby来了解Rails中的方法(以及ruby确实有效).当我看到诸如以下的方法调用时:

I am learning rails and going back to ruby to understand how methods in rails (and ruby really work). When I see method calls like:

validates validates :first_name, :presence => true

我很困惑.如何在ruby中编写接受符号或哈希值的方法. validates方法的源代码也令人困惑.有人可以为我简化在Ruby类和实例方法中使用符号作为参数的主题吗?

I get confused. How do you write methods in ruby that accept symbols or hashes. The source code for the validates method is confusing too. Could someone please simplify this topic of using symbols as arguments in ruby class and instance methods for me?

更新:

好人@Dave!但是我尝试的是这样的:

Good one @Dave! But What I was trying out was something like:

def full_name (:first_name, :last_name)
  @first_name = :first_name
  @last_name = :last_name
  p "#{@first_name} #{last_name}"
end

full_name("Breta", "Von Sustern")

显然会引发错误.我试图理解:如果符号与任何其他值一样,为什么将这样的符号作为参数传递是错误的?

Which obviously raises errors. I am trying to understand: Why is passing symbols like this as arguments wrong if symbols are just like any other value?

推荐答案

符号和哈希值是与其他值一样的值,可以像其他任何值类型一样传递.

Symbols and hashes are values like any other, and can be passed like any other value type.

回想一下ActiveRecord模型接受哈希作为参数;最终与此类似(不是那么简单,但最终还是一样的想法):

Recall that ActiveRecord models accept a hash as an argument; it ends up being similar to this (it's not this simple, but it's the same idea in the end):

class User
  attr_accessor :fname, :lname

  def initialize(args)
    @fname = args[:fname] if args[:fname]
    @lname = args[:lname] if args[:lname]
  end
end

u = User.new(:fname => 'Joe', :lname => 'Hacker')

这利用了不必将散列放在花括号{}中的优势,除非您需要消除参数的歧义(并且在跳过括号时也存在块解析问题).

This takes advantage of not having to put the hash in curly-brackets {} unless you need to disambiguate parameters (and there's a block parsing issue as well when you skip the parens).

类似地:

class TestItOut
  attr_accessor :field_name, :validations

  def initialize(field_name, validations)
    @field_name = field_name
    @validations = validations
  end

  def show_validations
    puts "Validating field '#{field_name}' with:"
    validations.each do |type, args|
      puts "  validator '#{type}' with args '#{args}'"
    end
  end
end

t = TestItOut.new(:name, presence: true, length: { min: 2, max: 10 })
t.show_validations

这将输出:

Validating field 'name' with:
  validator 'presence' with args 'true'
  validator 'length' with args '{min: 2, max: 10}'

从那里您可以开始了解这种工作方式.

From there you can start to see how things like this work.

这篇关于符号如何用于识别ruby方法中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆