Top 10 Ruby scenario questions
Try each one yourself first, then open the model answer.
1. A Rails index page runs a query for every row. How do you fix it?
Show answerHide answer
This is N+1. Preload associations with includes, and use a tool or logs to confirm the query count.
2. A form lets a user set an admin flag by adding a field. What protects against this?
Show answerHide answer
Strong parameters: permit only the attributes the user is allowed to change, and check authorisation.
3. Sending email makes the request slow. What do you do?
Show answerHide answer
Move it to a background job and make the job idempotent so retries do not send duplicates.
4. A method modifies a string passed in and surprises the caller. Why?
Show answerHide answer
Variables hold references and methods such as << or gsub! mutate the object. Duplicate before changing, or use non-mutating methods.
5. Two requests can create the same username despite a uniqueness validation. Why?
Show answerHide answer
The validation checks then writes, which can race. Add a unique database index and handle the violation.
6. A missing method call returns nil errors deep in the code. How can you make it safer?
Show answerHide answer
Use the safe navigation operator where absence is valid, fetch for required hash keys, and validate input early.
7. What would you do before using method_missing for dynamic attributes?
Show answerHide answer
Prefer define_method or explicit methods. If method_missing is needed, also define respond_to_missing? and call super for unknown names.
8. Processing a million records uses too much memory. What do you use?
Show answerHide answer
find_each or in_batches in Rails, so records are loaded in chunks.
9. A rescue block hides real errors. How should it be written?
Show answerHide answer
Rescue specific exception classes, never Exception, log the details, and re-raise what you cannot handle.
10. A migration locks a busy table. How would you reduce risk?
Show answerHide answer
Add indexes concurrently where supported, split schema changes from data backfills, and test on production-sized data.
