Strings to int conversion

P

Peter Wu

s = "1234" [0..1]
p s #> "12"
p s.to_i #> 12
s = s[1]
p s #> 50
p s.to_i #> 50

I can see the reason for this happening, but I don't want it to happen.

So how do I make it return 2 instead of 50?
 
A

Aaron Patterson

s = "1234" [0..1]
p s #> "12"
p s.to_i #> 12
s = s[1]
p s #> 50
p s.to_i #> 50

I can see the reason for this happening, but I don't want it to happen.

So how do I make it return 2 instead of 50?

"1234".split('')[1].to_i # => 2
 
J

Joel VanderWerf

Peter said:
s = "1234" [0..1]
p s #> "12"
p s.to_i #> 12
s = s[1]
p s #> 50
p s.to_i #> 50

I can see the reason for this happening, but I don't want it to happen.

So how do I make it return 2 instead of 50?

s[1,1]
s[1..1]
 
B

Bertram Scharpf

Hi,

Am Samstag, 27. Jun 2009, 05:55:20 +0900 schrieb Peter Wu:
s = "1234" [0..1]
s = s[1]
p s #> 50

I can see the reason for this happening, but I don't want it to happen.

The answer has already been given.

As far as I know Ruby 1.9 returns "2".

There's another [] operator that's not well known:

16[4] #=> 1 (the 4th bit is 1)

Bertram
 
R

Robert Schaaf

One of Ruby's problems is that it invites clever solutions, which are
computationally costly and create undue amounts of garbage.

How about

?> "1234"[1].chr
=> "2"
Cheers,

Bob Schaaf


s = "1234" [0..1]
p s #> "12"
p s.to_i #> 12
s = s[1]
p s #> 50
p s.to_i #> 50

I can see the reason for this happening, but I don't want it to
happen.

So how do I make it return 2 instead of 50?
 
D

David A. Black

Hi --

s = "1234" [0..1]
p s #> "12"
p s.to_i #> 12
s = s[1]
p s #> 50
p s.to_i #> 50

I can see the reason for this happening, but I don't want it to happen.

So how do I make it return 2 instead of 50?

Addendum to other answers:

In 1.9 it returns the character rather than the character code.


David

--
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Now available: The Well-Grounded Rubyist (http://manning.com/black2)
"Ruby 1.9: What You Need To Know" Envycasts with David A. Black
http://www.envycasts.com
 
D

Daniel DeLorme

Bertram said:
There's another [] operator that's not well known:

16[4] #=> 1 (the 4th bit is 1)

Wow, I've been using ruby for many years but there's
always something new to learn isn't it? Thanks.

Daniel
 
P

pierr

Peter said:
s = "1234" [0..1]
p s #> "12"
p s.to_i #> 12
s = s[1]
p s #> 50
p s.to_i #> 50

I can see the reason for this happening, but I don't want it to happen.

So how do I make it return 2 instead of 50?
p s[1].chr.to_i #=> 2
 

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,174
Messages
2,570,941
Members
47,476
Latest member
blackwatermelon

Latest Threads

Top