The problem with redirecting to a file or using a subshell or similar technique is that the yes command is infinite. There is no terminating condition other than killing the process. There are ways to do this with other commands but something like yes is going to be problematic.
Is yes a requirement or did you serve it up as an example of what you are trying to do?
Do you know how many "y"s you need? Filter the output with head to restrict the number of lines. yes | head -n 5 | command
When head closes its input after 5 lines, yes gets told its output has closed and it will stop. In the meantime, command is processing the output from head.
The problem, I believe, is not how to limit the output of yes; you've clearly demonstrated how to do that. I think the more difficult problem is doing that without using a pipe (thus preventing a 'broken pipe' from terminating yes).