Bfca16459c82a7836c3d5c8d79f0b640

I try to extract an id from a string. The string will look like "category-1337" and I want my result to be 1337. Surely I could use string slicing but I sometimes I need more power.

category_id = category_name.scan(/category-(\d+)/)[0][0]

Refactorings

No refactoring yet !

D41d8cd98f00b204e9800998ecf8427e

gra

December 18, 2008, December 18, 2008 13:25, permalink

No rating. Login to rate!
category_id = category_name.split("-")[1]
23132e1aa8457e11b243a43b578d51dc

Simo Niemelä

December 18, 2008, December 18, 2008 14:01, permalink

No rating. Login to rate!
category_id = category_name.split("-").last
A8d3f35baafdaea851914b17dae9e1fc

Adam

December 19, 2008, December 19, 2008 04:15, permalink

No rating. Login to rate!
category_id = category_name[/\d+$/]
F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

December 20, 2008, December 20, 2008 18:51, permalink

No rating. Login to rate!

This is really what scanf is for.. but i guess the stdlib require is kinda lame

require 'scanf'
category_id = category_name.scanf 'category-%d'
D7a31f22c11776898826f7c1ed0ff80a

mischamolhoek.myopenid.com

December 22, 2008, December 22, 2008 09:19, permalink

No rating. Login to rate!

or do something like this

category_id = category_name[/category-(\d+)/,1]
F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

December 22, 2008, December 22, 2008 17:27, permalink

No rating. Login to rate!

Gah! I thought scanf was implement in C but its not, so terrible Idea haha

Be072eb0e9f6f81c20541150cabce3ab

Ollie

December 23, 2008, December 23, 2008 05:46, permalink

No rating. Login to rate!

Although scanf solves this problem simply and effectively, in general I have always considered it inferior to regular expressions. As such, I have never learnt to use it nor care to (despite my admiration of those familiar with scanf (usually programmers of UNIX or C background)). OP, is my sentiment prevalent among your maintainers? If so, prefer the solution that uses the regular expression.

F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

December 23, 2008, December 23, 2008 06:58, permalink

No rating. Login to rate!

I think scanf is a little more verbose but its a little clearer IMO, but at the same time I expected it to be implemented in C which it is not! so I would put a big fat MEH on parsing such a simple string with scanf

F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

December 23, 2008, December 23, 2008 06:59, permalink

No rating. Login to rate!

ps. scanf implement the same formatting functionality that the printf family does ( or % in ruby's case), handy stuff

Your refactoring





Format Copy from initial code

or Cancel