I would like to prepend a '/' if the variable follow has a value otherwise if it is nil then keep it as nil
l2, follow = params[:all].split('/', 2)
follow = follow.nil? ? follow : "/#{follow}"
redirect_to "#{my_path(locale: locale, l2: l2)}#{rest}"
the params[:all] here could be a url path like
esp
esp/article/1
esp/article/1/author/1
EDIT: My approach works but would like to know if there is a better way
follow.nil? ? follow : "/#{follow}"
Since Ruby
has String#prepend method, the code can be refactored the following way:
follow && follow.prepend("/")
Or since Ruby 2.3
has safe navigation, it can be expressed even more concise:
follow&.prepend("/")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.