【问题标题】:The difference between dereferencing string instance variables and symbols in RubyRuby中解引用字符串实例变量和符号的区别
【发布时间】:2013-12-02 19:32:38
【问题描述】:

我正在使用 rspec 文件中的 let 函数。我想使用 let 函数来替换字符串实例变量的使用,就像我在下面的 @astr 中使用的那样。

describe "Static pages" do
  let (:str) { "Ruby on Rails Tutorial Sample App" }

 describe "Contact Page" do

it "should have title 'Contact'" do
    @astr = "Ruby on Rails Tutorial Sample App"
  visit '/static_pages/contact'
  expect(page).to have_title("#{@astr} | Contact")
end
end

...

变成了

it "should have title 'Contact'" do
  visit '/static_pages/contact'
  expect(page).to have_title("#{str} | Contact")
end

让我感到困惑的是为什么 #{str} 有效而 #{:str} 无效 - 取消引用符号 - 就像我们保留“@”一样对于#{@astr},为什么约定不适用于符号中的冒号?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    定义let(:str)...后,str成为一个方法。

    因此,当您在测试中调用 str 时,您调用的不是变量,而是返回您定义的内容的方法。

    在我看来,let 相对于实例变量的三个好处。

    1. 更明确。

    2. 它很懒惰。除非您调用它,否则该方法不会返回。但是变量总是被定义并存在于内存中。所以let效率更高。

    3. 只是我自己的感觉。 str,作为方法,在我的编辑器中显示方法颜色,而实例变量显示另一种。方法在我的代码中看起来更好更简洁。

    【讨论】:

    • 哦,好吧,所以'str'变成了一种方法。这很有意义。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-01-05
    • 2021-10-24
    • 2013-11-15
    • 2014-09-16
    • 2012-02-25
    • 1970-01-01
    • 2013-05-26
    • 2010-10-31
    相关资源
    最近更新 更多