Method and variable name is the same

后端 未结 4 406
难免孤独
难免孤独 2020-12-03 18:29

If both a method and a variable has the same name it will use the variable.

hello = \"hello from variable\"

def hello
  \"hello from method\"
end

puts hell         


        
4条回答
  •  Happy的楠姐
    2020-12-03 18:52

    This is more of a comment than an answer, but distinguishing between local variables and methods is vital if you're using an assignment method.

    class TrafficLight
      attr_accessor :color
    
      def progress_color
        case color
        when :orange
          #Don't do this!
          color = :red
        when :green
          #Do this instead!
          self.color = :orange
        else
          raise NotImplementedError, "What should be done if color is already :red? Check with the domain expert, and build a unit test"
        end
      end
    end
    
    traffic_light = TrafficLight.new
    traffic_light.color = :green
    traffic_light.progress_color
    traffic_light.color # Now orange
    traffic_light.progress_color
    traffic_light.color # Still orange
    

提交回复
热议问题