Ruby n00b

Soldato
Joined
24 Nov 2002
Posts
16,378
Location
38.744281°N 104.846806°W
I have a Ruby script, but I'm a little stuck.

I'm using page_content.scan to find something on a page but it returns an array. Ideally I just want a string return as there will be ONLY one result.

Secondly, I want an if loop, so that if "s" wasn't found don't have a hissy fit/do nothing and say print "unknown".

Thirdly, I'm using sleep(30) to pause the loop, but I want to rerun the loop on a keypress, possible?

Code:
open(url) {
  |page| page_content = page.read()
  s = page_content.scan(%r{Now:</strong> (.*?)</span>}m).flatten
  s.each {|s| puts s}
  }
 
Last edited:
if your array is called arr

Just index positon 0 ie arr[0]

prior to that test if array is empty with arr.empty? -> true

so I assume something like

if arr.empty? == true
'do something
else
'do something else
end


Then again I barely know what ruby is hehe but I can use google :)
 
Last edited:
Code:
require 'open-uri'

url = "url"


#loop {
  def whichs(url)
  open(url) {
  |page| page_content = page.read()
  ss = page_content.scan(%r{Now:</strong> (.*?)</span>}m).flatten
  ss.each {|ss| puts ss}
  }
end

puts "---------------------------------------"
  whichs(url) 

sleep(30); puts "Refreshing..."
#}

That's what I have - can't figure out the if empty? thing :(
 
ok as said not a ruby person

so ss.each {|ss| puts ss} writes each array indice of ss out to the console.

so just expand on this with the validity test

ie

if not ss.empty
ss.each {|ss| puts ss}
else
...

although if you only want array indice 0 then

if not ss.empty
{|ss[0]| puts ss[0]}
else
...

? Though i'm unsure of the pipes bit so couldn't you just do {puts ss[0]}
 
Last edited:
I've worked around that problem and ignore the others...

However, is there a quick way to convert &quot; to " from a screen scrape.

Code:
open(url) {
  |page| page_content = page.read()
  titles = page_content.scan(%r{<title>(.*?)</title>}m).flatten
  descriptions = page_content.scan(%r{<description>(.*?)</description>}m).flatten
  while count < number_to_fetch
#convert &quot; to "
   titles[count+1].each {|titles[count+1]| puts titles[count+1]}
    descriptions[count].each {|descriptions[count]| puts descriptions[count]}
    puts ""
    count += 1
  end
  }
 
Back
Top Bottom