0

I come across this piece of ruby code :

def link_to(link_text, url, mode=:path_only)
# You should add "!!" at the beginning if you're directing at the Sinatra url
    if(url_for(url,mode)[0,2] == "!!")
      trimmed_url = url_for(url,mode)[2..-1]
      "<a href=#{trimmed_url}> #{link_text}</a>"
    else
      "<a href=#{url_for(url,mode)}> #{link_text}</a>"
    end  
end  

def url_for url_fragment, mode=:full_url
  case mode
    when :path_only
#cut for brievity. The rest of the function gets rack params and renders full url (or not)

I have no clue what this line of code does : (url_for(url,mode)[0,2] == "!!")

4
  • Tip: Method calls are like f(x) while constructs like if are expressed as if x or if (x) if parentheses are used. The space is a small detail, but it makes it read differently. Commented Jan 21, 2021 at 18:00
  • I know. It's not my code. And strangely.... it does work. Commented Jan 21, 2021 at 18:01
  • Oh, it does work, it's just that at a glance this looks like a method call to a method named if, which it is not. Tools like Rubocop can help "lint" your code and find issues like this. Commented Jan 21, 2021 at 18:02
  • Did Rubocop stop at Ruby 2.3? Commented Jan 21, 2021 at 18:34

1 Answer 1

3

This code:

url_for(url,mode)[0,2] == "!!"

Checks that the first (offset 0) two characters (,2) are equivalent to "!!". This is now something you can express as:

url_for(url,mode).start_with?("!!")

Which might make it easier to understand.

The String#[] method has two forms relevant to understanding this:

"hello"[0] # Character index
# => "h"
"hello"[0,1] # Equivalent to above
# => "h"
"hello"[0,2] # Su
# => "he"
Sign up to request clarification or add additional context in comments.

3 Comments

The first one is readable if you're used to the notation, but the start_with? form is abundantly clear.
"two forms" might be an understatement. There are also the range, string and regex (optionally with capture group) variants.
@3limin4t0r True, added some clarification here as to the ones being focused on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.