Hopefully someone can come along and improve upon this. But here's a start.
One trick is to use the construct:
$$\xdef\pds{\the\predisplaysize}$$
which will obtain the width up to where the previous line ended (with some adjustments, see section 24.3 of "TeX by Topic" for further details). This may seem an odd approach, but this is how to put it into action:
\newcommand\answerbox[1]{%%
\bgroup
\abovedisplayskip0pt%%
\belowdisplayskip0pt%%
\abovedisplayshortskip0pt%%
\belowdisplayshortskip0pt%%
$$\xdef\pds{\the\predisplaysize}$$%
\par\prevdepth0pt{\par\kern-2\baselineskip\parskip0pt}%%
\noindent
\kern\pds\kern-2em\fbox{%%
\rule{\dimexpr\linewidth-\pds+2em-2\fboxrule-2\fboxsep}{0pt}%%
\rule{0pt}{#1}}%%
\egroup}
In this, the grouping is necessary to restrict the adjusted values of the \abovedisplayskip et al. to the scope of your macro.
Regarding the adjustments of 2em, see section 24.3 of TeX by Topic.
\documentclass{article}
\usepackage{pgffor}
\setlength\parindent{0pt}
\usepackage{lipsum}
\newcommand\answerbox[1]{%%
\bgroup
\abovedisplayskip0pt%%
\belowdisplayskip0pt%%
\abovedisplayshortskip0pt%%
\belowdisplayshortskip0pt%%
$$\xdef\pds{\the\predisplaysize}$$%
\par\prevdepth0pt{\par\kern-2\baselineskip\parskip0pt}%%
\noindent
\kern\pds\kern-2em\fbox{%%
\rule{\dimexpr\linewidth-\pds+2em-2\fboxrule-2\fboxsep}{0pt}%%
\rule{0pt}{#1}}%%
\egroup}
\begin{document}
\foreach \myn in {0,5,10,15,20,25}
{
\par
\foreach \myk in {0,...,\myn} {a }%%
\answerbox{2ex}\vspace{2ex}%%
}
\lipsum[1-2]
\end{document}

The use of pgffor and lipsum are merely for presentation and not necessary for the macro \answerbox.
\item Write something \answerbox{2cm}may or may not reach the right hand margin. – Alasdair Feb 23 '15 at 03:02\dotfillor\hrulefillare a solution (see also https://tex.stackexchange.com/a/155960). And there is the excellent packageexam, even though it has no perfect solution for this question. – hplieninger Jun 07 '17 at 15:42