category_id = category_name.scan(/category-(\d+)/)[0][0]
Refactorings
No refactoring yet !
Simo Niemelä
December 18, 2008, December 18, 2008 14:01, permalink
category_id = category_name.split("-").last
Tj Holowaychuk
December 20, 2008, December 20, 2008 18:51, permalink
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'
mischamolhoek.myopenid.com
December 22, 2008, December 22, 2008 09:19, permalink
or do something like this
category_id = category_name[/category-(\d+)/,1]
Tj Holowaychuk
December 22, 2008, December 22, 2008 17:27, permalink
Gah! I thought scanf was implement in C but its not, so terrible Idea haha
Ollie
December 23, 2008, December 23, 2008 05:46, permalink
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.
Tj Holowaychuk
December 23, 2008, December 23, 2008 06:58, permalink
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
Tj Holowaychuk
December 23, 2008, December 23, 2008 06:59, permalink
ps. scanf implement the same formatting functionality that the printf family does ( or % in ruby's case), handy stuff
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.