首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > Ruby Rails >

ruby施用技巧

2012-12-22 
ruby使用技巧翻出来一篇很老的东西,有些已经不用了,总之,抄回来,看看吧1 - Extract regular expression ma

ruby使用技巧
翻出来一篇很老的东西,有些已经不用了,总之,抄回来,看看吧

1 - Extract regular expression matches quickly

A typical way to extract data from text using a regular expression is to use the match method. There is a shortcut, however, that can take the pain out of the process:




3 - Format decimal amounts quickly

Formatting floating point numbers into a form used for prices can be done with sprintf or, alternatively, with a formatting interpolation:


4 - Interpolate text quickly

The formatting interpolation technique from #3 comes out again, this time to insert a string inside another:



You can use an array of elements to substitute in too:



5 - Delete trees of files

Don't resort to using the shell to delete directories. Ruby comes with a handy file utilities library called FileUtils that can do the hard work:




# Output:
#   Added to queue
#   Added to queue
#   ["hello", "world"]

2009 Update: Be careful here - this one can sting you in the butt if your first expression returns nil even when it works. A key example of this is with the puts method which returns nil even after printing the supplied arguments.
10 - Do something only if the code is being implicitly run, not required

This is a very common pattern amongst experienced Ruby developers. If you're writing a Ruby script that could be used either as a library OR directly from the command line, you can use this trick to determine whether you're running the script directly or not:



12 - Use ranges instead of complex comparisons for numbers

No more if x > 1000 && x < 2000 nonsense. Instead:



puts x == 10 ? "x is ten" : "x is not ten"

# Or.. an assignment based on the results of a ternary operation:
LOG.sev_threshold = ENVIRONMENT == :development ? Logger::DEBUG : Logger::INFO

15 - Nested Ternary Operators

It can be asking for trouble but ternary operators can be nested within each other (after all, they only return objects, like everything else):


I commonly see methods using this sort of pattern:

 

热点排行