Ruby练习三

Q1: attr_accessor_with_history

attr_accessor uses metaprogramming to create getters and setters for object attributes on the fly. Define a method attr_accessor_with_history that provides the same functionality as attr_accessor but also tracks every value the attribute has ever had:

class Foo attr_accessor_with_history :bar end f = Foo.new # => #<Foo:0x127e678> f.bar = 3 # => 3 f.bar = :wowzo # => :wowzo f.bar = 'boo!' # => 'boo!' f.bar_history # => [nil, 3, :wowzo, 'boo!']

> Here are some hints and things to notice to get you started:
1. The first thing to notice is that if we define attr_accessor_with_history in class Class, we can use it as in the snippet above. This is because in Ruby a class is simply an object of class Class.
2. The second thing to notice is that Ruby provides a method class_eval that takes a string and evaluates it in the context of the current class, that is, the class from which you're calling attr_accessor_with_history.  This string will need to contain a method definition that implements a setter-with-history for the desired attribute attr_name.
3. bar_history should always return an Array of elements, even if no values have been assigned yet.
4. Don't forget that the very first time the attribute receives a value, its history array will have to be initialized.
5. Don't forget that instance variables are referred to as @bar within getters and setters.
6. Although the existing attr_accessor can handle multiple arguments (e.g. attr_accessor :foo, :bar), your version just needs to handle a single argument.  However, it should be able to track multiple instance variables per class, with any legal class names or variable names, so it should work if used this way:
7. History of instance variables should be maintained separately for each object instance. that is, if you do:

> ```ruby
class SomeOtherClass attr_accessor_with_history :foo
    attr_accessor_with_history :bar
end

f = Foo.new f.bar = 1 f.bar = 2 f = Foo.new f. bar = 4 f.bar_history

> then the last line should just return [nil,4], rather than [nil,1,2,4]. Here is some skeleton code:

> ```ruby
class Class
 def attr_accessor_with_history(attr_name)
   attr_name = attr_name.to_s   # make sure it's a string
   attr_reader attr_name        # create the attribute's getter
   attr_reader attr_name+"_history" # create bar_history getter
   class_eval "your code here, use %Q for multiline strings"
 end
end

class Foo attr_accessor_with_history :bar end f = Foo.new f.bar = 1 f.bar = 2 f.bar_history # => if your code works, should be [nil,1,2]

####My Example Code

```ruby
class Class
    def attr_accessor_with_history(attr_name)
        attr_name = attr_name.to_s
        attr_reader attr_name
        attr_reader attr_name + "_history"

        #our setter code here
        class_eval %Q{
            def #{attr_name}=(attr_name)
                @#{attr_name} = attr_name

                unless @#{attr_name + "_history"}
                    @#{attr_name + "_history"} = []
                    @#{attr_name + "_history"} << nil
                end
                @#{attr_name + "_history"} << attr_name
            end
        }
    end
end

class Test
    attr_accessor_with_history :sample
end

t = Test.new
t.sample = "test"
t.sample = 1
t.sample = :abc
print t.sample_history

Q2: Extend Currency Conversion Example

Extend the currency-conversion example from the text so that you can write: 5.dollars.in(:euros), 10.euros.in(:rupees)

You should support the currencies 'dollars', 'euros', 'rupees', and 'yen' where the conversions are: 1 rupee to 0.019 dollars, 1 yen to 0.013 dollars, 1 euro to 1.292 dollars.

Both the singular and plural forms of each currency should be acceptable, e.g. 1.dollar.in(:rupees) and 10.rupees.in(:euro) should work. You can use the code below (http://pastebin.com/agjb5qBF) as a starting point.

class Numeric @@currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019} def method_missing(method_id) singular_currency = method_id.to_s.gsub( /s$/, '') if @@currencies.has_key?(singular_currency) self * @@currencies[singular_currency] else super end end end

####My Example Code
```ruby
class Numeric
    @@currencies = {'dollar' => 1.000,'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019}
    
    def method_missing(method_id)
        sigular_currency = method_id.to_s.gsub(/s$/,'')
        if @@currencies.has_key?(sigular_currency)
            self * @@currencies[sigular_currency]
        else
            super
        end
    end

    def in(currency)
        sigular_currency = currency.to_s.gsub(/s$/,'')
        self / @@currencies[sigular_currency]       
    end

end

puts 5.dollars.in(:euros)
puts 10.euros.in(:rupees)

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏跟着阿笨一起玩NET

动态调用WebService

http://linglong117.blog.163.com/blog/static/277145472009127514463/

551
来自专栏ml

springMVC拦截器和过滤器总结

拦截器: 用来对访问的url进行拦截处理 用处: 权限验证,乱码设置等 spring-mvc.xml文件中的配置: <beans xmlns="http://w...

2707
来自专栏pangguoming

在Spring MVC中使用注解的方式校验RequestParams

1794
来自专栏osc同步分享

springmvc 拦截器、国际化、验证

springmvc 拦截器 继承了HandlerIntercepter的类可以作为拦截器类: package com.yawn.intercepter; im...

3327
来自专栏JAVA技术站

JFinal 自动路由注册,节省开发时间 原

       路由自动注册实现起来挺简单的,只需拿到所有的Controller配置到路由就行,代码如下

331
来自专栏张善友的专栏

Spacebuilder在Mono上运行修改备忘

Spacebuilder 是一个asp.net mvc3项目,使用到了Combres,Combres依赖于dotless,然后在Spacebuilder的项目没...

1946
来自专栏javathings

Spring Boot 拦截器如何实现

Spring Boot 的拦截器概念上和 Servlet Filter 很像,拦截发送到 Controller 的请求和给出的响应。

861
来自专栏c#开发者

遍列schema代码

Code class XmlSchemaTraverseExample {     static void Main()     {         ...

3395
来自专栏服务端技术杂谈

自己写个类加载器

获取指定包下所有的类,需要将包名转换为文件路径,读class文件或者jar包,再去进行类加载:

853
来自专栏一个会写诗的程序员的博客

《JSP极简教程》c:forEach 如何输出序号

643

扫码关注云+社区