Simple refactor?


As I continue learning to program, I am finding things I think can
probably be done in a better way. The following code seems like
programmers must run into all the time and I am wondering if there is a
better way to write the code in this situation (it seems very repetitive
to me). I'm having fun and trying to get better at this....

    if !session[:subject_id].blank?
        @subject_id = session[:subject_id]

    if !session[:book_id].blank?
      @book_id = session[:book_id]

    if !session[:chapter_id].blank?
      @chapter_id = session[:chapter_id]

    if !session[:section_id].blank?
      @section_id = session[:section_id]

    if !session[:subsection_id].blank?
      @subsection_id = session[:subsection_id]

    if !session[:minisection_id].blank?
      @minisection_id = session[:minisection_id]

Is there a better way??




[:subject_id, :book_id, :chapter_id, :section_id, :subsection_id, :minisection_id].each do |k|
“@#{k.to_s}” = session[k] if session[k].present?

@subject_id = session[:subject_id] if session[:subject_id].present?
@book_id = session[:book_id] if session[:book_id].present?
@chapter_id = session[:chapter_id] if session[:chapter_id].present?
@section_id = session[:section_id] if session[:section_id].present?
@subsection_id = session[:subsection_id] if session[:subsection_id].present?
@minisection_id = session[:minisection_id] if session[:minisection_id].present?

Sorry -- really not sure what's supposed to be happening here --
you're assigning to a string literal?

apparently, he meant…

instance_variable_set("@#{k.to_s}", session[k]) if session[k].present?

kind regards -botp

botp wrote in post #1097518:

def set_instance_var_with_session_value variable

instance_variable_set("@#{variable.to_s}", session[variable]) if session[variable].present?


and you will have a general method for this, for any symbol.

for example call set_instance_var_with_session_value(:subject_id)

it should work!