Kir
Kir

Reputation: 8111

Get id from string with Ruby

I have strings like this:

How to get ids (205193, 183863, 1003) from it with Ruby?

Upvotes: 0

Views: 1636

Answers (5)

Lee
Lee

Reputation: 144206

s = "/detail/205193-foo-var-bar-foo.html"
num = (s =~ /detail\/(\d+)-/) ? Integer($1) : nil

Upvotes: 0

DigitalRoss
DigitalRoss

Reputation: 146231

Just say s[/\d+/]


[
 "/detail/205193-foo-var-bar-foo.html",
 "/detail/183863-parse-foo.html",
 "/detail/1003-bar-foo-bar.html"
].each { |s| puts s[/\d+/] }

Upvotes: 4

girasquid
girasquid

Reputation: 15506

One easy way to do it would be to strip out the /detail/ part of your string, and then just call to_i on what's left over:

"/detail/1003-bar-foo-bar.html".gsub('/detail/','').to_i # => 1003

Upvotes: 1

Doon
Doon

Reputation: 20232

could also do something like this

"/detail/205193-foo-var-bar-foo.html".gsub(/\/detail\//,'').to_i
 => 205193

Upvotes: 3

bowsersenior
bowsersenior

Reputation: 12574

regex = /\/detail\/(\d+)-/
s = "/detail/205193-foo-var-bar-foo.html"
id = regex.match s  # => <MatchData "/detail/205193-" 1:"205193">
id[1]               # => "205193"
$1                  # => "205193"

The MatchData object will store the entire matched portion of the string in the first element, and any matched subgroups starting from the second element (depending on how many matched subgroups there are)

Also, Ruby provides a shortcut to the most recent matched subgroup with $1 .

Upvotes: 1

Related Questions