0

How can I convert these:

[172592596,93038592,154137572]

To look like these:

['172592596','93038592','154137572']
1
  • 5
    Are you saying you have an array of ints and want to turn it into an array of strings? Because that's what your body seems to say, but the title says the opposite of that... Commented Oct 22, 2010 at 20:51

2 Answers 2

11

If you want to turn an array of ints into an array of strings, you can do so easily using map and to_s.

arr = [172592596,93038592,154137572]
arr.map {|x| x.to_s}
#=> ["172592596", "93038592", "154137572"]

Since this is rails, you can also do (will also work in plain ruby if the version is at least 1.8.7):

arr.map(&:to_s)

To get the same result.

Sign up to request clarification or add additional context in comments.

2 Comments

How can I convert ["333","444"] to [{"id":"333","id":"444"}?
@Jonathan: {"id":"333","id":"444"} is a syntax error. You can't use string keys using the : syntax with string keys. If you change it {"id" => "333", "id" => "444"} it still doesn't work because you can't have duplicate keys in a hash.
0

Try this!

b = []
a = [172592596,93038592,154137572]
a.each {|a1| b << a1.to_s}
b will return ["172592596", "93038592", "154137572"]

You can also use collect! same as map like @sepp2k suggested.

a = [172592596,93038592,154137572]
a.collect! {|x| x.to_s}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.