0

I have this array of team names:

teams = ["Atlanta Hawks","Boston Celtics","Brooklyn Nets"]

I want to iterate over teams array, and insert each team into the css selector for 'title':

teams.each do |team_name|
    basketball_team_links << basketball_teams.css("a[class='lnkBeatWriterLeague'][title=#{team_name}]").map { |link| link['href'] }
end

Obviously my approach is flawed, and I can't figure out how to read in the |team_name| variable.

0

1 Answer 1

4

have you tried with:

"a[class='lnkBeatWriterLeague'][title='#{team_name}']"

or:

"a[class='lnkBeatWriterLeague'][title=\"#{team_name}\"]"

or:

%Q{a[class='lnkBeatWriterLeague'][title="#{team_name}"]}

or:

"a[class='lnkBeatWriterLeague'][title='" + team_name + "']"

EDIT:

Adding a note on some corner cases that should be considered, as suggested by @Amadan in the comments.

Whether the teams strings come from a user or not, you might have apostrophes and quotes in them.
There are two simple ways to correctly escape them:

require 'cgi'
CGI.escapeHTML "input string"

require 'json'
"input string".to_json
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, as I'm sure you are aware...they all worked.
Caveat: each of them will break under certain circumstances: O'Reilly's Team, Sadist\"User, Jackie "Slugger" Jameson. Escape your team_name using CGI.escapeHTML, use team_name.to_json to also get quotes (requiring cgi and json, respectively), or just gsub your string into submission to be on the safe side. "Psh, I'll never have apostrophes in my string" will bite you almost every time. :) (Of course, you should choose inner quotes to match the escaping method you employ)

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.