Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

ruby not understanding arguments provided to a method

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] == "!!")

question from:https://stackoverflow.com/questions/65833176/ruby-not-understanding-arguments-provided-to-a-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...