When you first discover Ruby on Rails, some things might strike you right away: namely the large number of enumerable methods and the blocks to run co

Make streaming APIs easy with enumerable methods

submited by
Style Pass
2025-01-17 20:00:07

When you first discover Ruby on Rails, some things might strike you right away: namely the large number of enumerable methods and the blocks to run code in the middle of another method. Those features helped me translate my thoughts directly into code — and quickly made Ruby my favorite programming language.

Enumerables are great. You can use them to map, filter, reduce, and easily transform your data. Any method that returns an enumerable collection gives you that power without needing much work.

A method that yields values to a block can do more powerful things, but makes transformation harder. Any processing you want to do goes into the block, which doesn't feel as natural as chaining enumerable methods together. You have to think inside out (or even thread a block through multiple methods) before you get to the code that uses it.

Many large language model APIs, like the OpenAI chat API, can stream text back to you as it's generated. This is nice! You don't have to wait multiple seconds (or longer!) for a full response — you get feedback immediately. In most Ruby clients to these APIs, bits of text are yielded back to you one by one using a block.

Leave a Comment