Rails 3: Multiply each char of a string
Given a string @t = "123456789"
, how can I cycle each char of the string and multiply i开发者_开发知识库t by a defined number?
I've tried @t[0].to_i * number
.
thanks
@t = "123456789".split(//)
@t[0].to_i * number
You can use the each_char block method:
num = 2
@t = "123456789"
@t.each_char {|ch| puts(ch.to_i * num) }
@t.chars{|c| puts c.to_i * 5 }
5
10
15
20
25
30
35
40
45
If you are just wanting to print them out then this works.
@t.chars {|c| puts c.to_i * number}
If you are wanting to make it a new string then
@t.chars.map { |c| c.to_i * number }.join
Some References that may help you.
For the first .chars method in http://www.ruby-doc.org/core/classes/String.html
For the second .chars returns a enumerator that .map can be called on. http://www.ruby-doc.org/core/classes/Enumerable.html
Hope this helps.
精彩评论