Ruby String Learning 2

Source: Internet
Author: User

Include a table but or a variable in a ruby string. To replace an expression or variable with a different value

1 Printf-style methods like Java or Python

Template ='Oceania have always been at the war with%s.'Template%'Eurasia' #= = "Oceania have always been at the war with Eurasia."Template%'Eastasia' #= = "Oceania have always been at the war with Eastasia."
'To 2 decimal places:%.2f'%Math::P i# = "to 2 decimal places:3.14"

'zero-padded:%.5d' %Math::P i #= "zero-padded:00003"

2 or use the ERB, because I use the IDE, so the last line uses the kernel.binding, if you are in IRB, you can only use the binding

' Erb '  = erb.new%q{chunky <%= food%>"bacon"= Template.result ( kernel.binding)

3 Flipping a string

 s =  .sdrawkcab si gnirts siht   " s.reverse  #   = "This string is backwards."  s #   = ". Sdrawkcab si gnirts siht"  s.reverse!  #   = "This string is backwards."  s #   = "This string is backwards."  
" order. Wrong The in is words these " S.split (/(\s+)/). reverse!. Join ('#  = ' These words is in the wrong order. " s.split (/\b/). reverse!. Join ('#  = ' These words is in the wrong. Order "

(\s+) and \s+, (\s+) The matching spaces are included in the return list

" Three Little Words ". Split (/\s+/)#  = [" Three "," little "," words "]"Three Little Words". Split (/(\s+)/)# + = [" Three "," "," Little "," "," words "]

Ruby String Learning 2

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.