Preguntas y respuestas de entrevista mas solicitadas y pruebas en linea
Plataforma educativa para preparacion de entrevistas, pruebas en linea, tutoriales y practica en vivo

Desarrolla tus habilidades con rutas de aprendizaje enfocadas, examenes de practica y contenido listo para entrevistas.

WithoutBook reune preguntas de entrevista por tema, pruebas practicas en linea, tutoriales y guias comparativas en un espacio de aprendizaje responsivo.

Preparar entrevista

Ruby On Rails preguntas y respuestas de entrevista

Question: How will you implement Observer Pattern in Ruby on Rails?
Answer:

Lets review first what an observer pattern is all about.  

The observer pattern (sometimes known as publish/subscribe) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.

You might have used them in other programming languages as listener objects. You use them whenever a button is clicked on the screen and a method gets called automatically. 

As in the case of the singleton pattern, the observer pattern is also implemented by mixing in a module. 

In the Ruby implementation, the notifying class mixes in the Observable module, which provides the methods for managing the associated observer objects.

And, the observers must implement the update method to receive notifications.

Heres an example. Say you want to send an SMS alert to users if a company stock drops then you can do something like this:

require "observer" 
require "observer" 
  class Ticker # Periodically fetch a stock price 
    include Observable 
 	attr_accessor :price 
    def initialize symbol, price 
      @symbol = symbol 
  	@price = price 
	end
    
	def run 
      lastPrice = nil 
      loop do 
        @price = @price+Random.rand(11) 
        print "Current price: #{price}n" 
        if @price != lastPrice 
          changed                 # notify observers 
          lastPrice = @price 
           notify_observers(Time.now, @price) 
         end
       end 
    end 
  end
 
  class Warner
     def initialize ticker  
     ticker.add_observer(self)   # all warners are observers     
  end   
end 
  
class SMSAlert < Warner     
   def update time, price       # callback for observer         
      print "--- #{time.to_s}: SMS Alert for price: #{price}n"     
   end   
end  

class EmailAlert < Warner     
   def update time, price       # callback for observer         
      print "+++ #{time.to_s}: Email Alert Price changed to #{price}n"    
   end
 end

Guardar para repaso

Guarda este elemento en marcadores, marcalo como dificil o agregalo a un conjunto de repaso.

Abrir mi biblioteca de aprendizaje
Es util? Si No

Lo mas util segun los usuarios:

Copyright © 2026, WithoutBook.