定义变量后自动更改变量值 [英] automatically changing variable values once they are defined

查看:52
本文介绍了定义变量后自动更改变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一些代码来满足此 RSpec 要求(已删节)

I am trying to write some code to satisfy this RSpec requirement (abridged)

@book = Book.new

@book.title = "inferno"
@book.title.should == "Inferno"

我不知道如何让 @book.title 在定义后自动从inferno"变为Inferno",我也不知道去哪里找.我已经查看了实例变量的文档和初始化的文档,但解决方案从两者中都变得清晰.

I am not sure how one would make @book.title change from "inferno" to "Inferno" automatically once it is defined, nor do I know where to look. I have looked at the documentation for instance variables and the documentation for initialization, but the solution became clear from neither.

推荐答案

你可以通过重写 setter 方法来实现:

You can acheive this by overriding the setter method:

class Book < ActiveRecord::Base
  # other stuff ...

  def title=(str)
    write_attribute(:title, str.capitalize)
  end
end

或者:

class Book < ActiveRecord::Base
  # other stuff ...

  def title=(str)
    self[:title] = str.capitalize
  end
end

您可能需要考虑额外的处理,因为 String#capitalize 可能不足以满足您的需求.示例:

You may need to take additional processing into consideration, since String#capitalize may not be sufficient for your needs. Example:

'foo'.capitalize
#=> "Foo"

'foo of bar'.capitalize
#=> "Foo of bar"

一种可能的解决方案如下:

One possible solution for this would be as follows:

'foo'.split.map(&:capitalize).join(' ')
#=> "Foo"

'foo of bar'.split.map(&:capitalize).join(' ')
#=> "Foo Of Bar"

但请注意,这会带来不同的问题.最值得注意的是,这将丢弃任何前导、尾随和重复的空格:

But be aware that this brings about different problems. Most notably, this will discard any leading, trailing and repeated whitespace:

' foo of     bar '.split.map(&:capitalize).join(' ')
#=> "Foo Of Bar"

您必须自己决定这是否满足您的需求,但您已了解基本概念.

You will have to decide for yourself whether this meets your needs or not, but you get the basic idea.

这篇关于定义变量后自动更改变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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