【问题标题】:Understanding about proc class了解proc类
【发布时间】:2012-03-07 17:07:54
【问题描述】:

我正在学习 Ruby Proc 课程。我不明白为什么要执行“def state =”方法。

我也想知道为什么 "t1.state = 1" 以 "def state=(1)" 结尾

我不明白 "def state" 和 "def state=" 之间的区别?

我可以理解这个连接“&proc>proc>proc.call”。

    # -*- coding: utf-8 -*-
    class Terminal
      def initialize
        @connected = []
        @current_state = nil
      end
      def connect(&proc)
        @connected << proc
      end
      def current_input_terminal(terminal)
        connect do |hoge|
          terminal.state = hoge
        end
      end
      def state=(current)
        if current != 0 && current != 1
          raise(ArgumentError, "input 0 or 1")
        end
        if @current_state != current
          @current_state = current
          @connected.each do |i|
            i.call(current)
          end
        end
      end
      def state
        @current_state
      end
    end

    t1 = t2 = Terminal.new()
    t1.current_input_terminal(t2)
    t1.state = 1
    puts(t2.state,t1.state)

【问题讨论】:

  • def state 是吸气剂,而def state=(state) 是二元机
  • setter/getter... 是如何设置属性和使用它。我能够了解。谢谢你fl00r

标签: ruby proc


【解决方案1】:

这个表达式:

Terminal.new.state = 1

将调用方法def state=(current)

还有这个表达

puts Terminal.new.state 

将调用方法def state或读取数据

【讨论】:

  • 谢谢你,梅加斯。最后我想出了理解。
猜你喜欢
  • 2013-12-26
  • 2010-11-26
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
  • 2014-01-21
  • 2013-08-09
  • 1970-01-01
相关资源
最近更新 更多