gpt4 book ai didi

ruby-on-rails - 当我们在 View 中访问未定义的实例变量时,为什么 Rails 不抛出异常?

转载 作者:行者123 更新时间:2023-12-02 14:51:26 25 4
gpt4 key购买 nike

假设我们有以下实现:

app/controllers/cars_controller.rb

class CarsControllers < ApplicationController
def index
@test = '7'
end
end

应用/views/cars/index.html.erb

My test variable is <%= @test %>.
Here is an undefined variable <%= @test2 %>.

为什么访问 @test2 不会抛出异常(假设我们正在尝试访问实例变量)?

最佳答案

未定义的实例变量值永远是nil,如果你访问它,它不会抛出任何异常,而局部变量如果没有定义它会抛出异常,如果你想检查实例变量是否被赋值,你可以使用 .present? 方法。

简单的例子

实例变量

2.5.1 :009 > @undefined
=> nil
2.5.1 :010 > @undefined.present?
=> false
2.5.1 :011 > defined? @undefined
=> nil

2.5.1 :014 > @defined = "test"
=> "test"
2.5.1 :015 > @defined.present?
=> true
2.5.1 :016 > defined? @defined
=> "instance-variable"

局部变量

2.5.1 :017 > undefined_local
Traceback (most recent call last):
1: from (irb):17
NameError (undefined local variable or method `undefined_local' for main:Object)
2.5.1 :018 > undefined_local.present?
Traceback (most recent call last):
1: from (irb):18
NameError (undefined local variable or method `undefined_local' for main:Object)
2.5.1 :019 > defined? undefined_local
=> nil
2.5.1 :020 > defined_local = "test"
=> "test"
2.5.1 :021 > defined? defined_local
=> "local-variable"

希望这足以理解这个概念

关于ruby-on-rails - 当我们在 View 中访问未定义的实例变量时,为什么 Rails 不抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55507816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com