0

我正在学习 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)
4

1 回答 1

0

这个表达式:

Terminal.new.state = 1

将调用方法def state=(current)

而这个表达

puts Terminal.new.state 

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

于 2012-03-07T18:24:15.673 回答