shorter form of concat

  • Thread starter SpringFlowers AutumnMoon
  • Start date
S

SpringFlowers AutumnMoon

the following line will concat "1" all the way to "10"... but is there
a shorter way... like x . y or must it be this long?


p (1..10).inject{|x,y| x.to_s + y.to_s}

also... x.to_s + y
won't cause y to convert to a string?
 
T

Tim Hunter

SpringFlowers said:
the following line will concat "1" all the way to "10"... but is there
a shorter way... like x . y or must it be this long?


p (1..10).inject{|x,y| x.to_s + y.to_s}
(1..10).to_a.join


also... x.to_s + y
won't cause y to convert to a string?

No.
 
D

Day

This is not pretty, but...

x = 1
y = 10
string = "#{x}#{y}"
puts string => 110

I'm not sure I'd use that in production code, but there it is...


Ben
 
7

7stud --

SpringFlowers said:
what i mean is, any shorter way to concat two numbers? something
similar to x . y

class Fixnum
def a(num)
return sprintf("%s%s", self, num)
end
end

x = 3
y = 4
puts x.a(y)

--output:--
34
 
S

SpringFlowers AutumnMoon

7stud said:
class Fixnum
def a(num)
return sprintf("%s%s", self, num)
end
end

x = 3
y = 4
puts x.a(y)

--output:--
34


thanks. or this one works too:

p (1..10).inject{|x,y| "#{x}#{y}"}
 
M

Moises Trovo

[Note: parts of this message were removed to make it a legal post.]

thanks. or this one works too:

p (1..10).inject{|x,y| "#{x}#{y}"}

I think its better with a .to_a.join, depending on what you want it could be
more legible than the .inject one and equally customizable.
 
R

Robert Klemme

thanks. or this one works too:

p (1..10).inject{|x,y| "#{x}#{y}"}

If you use #inject, then you should rather do

irb(main):003:0> (1..10).inject("") {|s,x| s << x.to_s}
=> "12345678910"

or

irb(main):004:0> require 'stringio'
=> true
irb(main):005:0> (1..10).inject(StringIO.new) {|s,x| s << x}.string
=> "12345678910"


This is - at least in theory - much more efficient than repeated string
interpolation.

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,282
Messages
2,571,404
Members
48,096
Latest member
Kenkian2628

Latest Threads

Top