简体   繁体   中英

Ruby statement confusion regarding -array indexes and ranges

I have a text_parts variable that get populated as follows:

text_parts = r[:database_field].split('.')

The text_parts now has an array of words that were actually split by periods in the database. What does the below statement mean in ruby? I found it in the old codebase and need an explanation of what it does.

text_parts[-3].nil? ? "" : text_parts[-1*text_parts.length..-3].join('.')

Thank you in advance.

It takes the elements of text_parts from the first one up to the third from the last, and joins them with "." (If text_parts has less than three elements, then it returns an empty string).

It is clearly not a code written by (anyone who qualifies as) a professional. It is very bad.

  • First, since it is ensured that all elements of text_parts are strings, you do not need to consider cases where some of the elements are nil or false . Therefore, you do not need to use nil? . The condition can be text_parts[-3] ? ... : ... text_parts[-3] ? ... : ... , with the two cases switched.
  • Second, -1*text_parts.length should be simply written 0 .
  • Third, if text_parts is shorter than three, then text_parts[0..-3] would be an empty array, so the condition was not necessary in the first place.

In short, a better way to write this is:

text_parts[0..-3].join(".")

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM