J'ai un tableau:Convertir un tableau d'entiers en un tableau de chaînes dans Ruby?
int_array = [11,12]
je dois le convertir en
str_array = ['11','12']
Je suis nouveau à cette technologie
J'ai un tableau:Convertir un tableau d'entiers en un tableau de chaînes dans Ruby?
int_array = [11,12]
je dois le convertir en
str_array = ['11','12']
Je suis nouveau à cette technologie
str_array = int_array.map(&:to_s)
Je reçois toujours la sortie en tant que [11, 12] .. je n'ai pas aidé –
Comment vérifiez-vous le type de votre sortie? – srboisvert
Cela fonctionne dans Rails car il ajoute le symbole # to_proc – dylanfm
str_array = int_array.collect{|i| i.to_s}
n'a pas aidé .. :( –
Cela a bien fonctionné pour moi – srboisvert
son fonctionnement bien pour moi aussi .. merci –
Mise en service irb
irb(main):001:0> int_array = [11,12]
=> [11, 12]
irb(main):002:0> str_array = int_array.collect{|i| i.to_s}
=> ["11", "12"]
Votre problème est probablement ailleurs. Peut-être une confusion de portée?
x = [1,2,3,4,5,6,7,8,9,10] # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = 1,2,3,4,5 # => ["1", "2", "3", "4", "5"]
carte et fonctions fonctionnera recueillir la même chose ici.
int_array = [1, 2, 3]
str_array = int_array.map { |i| i.to_s }
=> str_array = ['1', '2', '3']
Vous pouvez acheive cela avec une ligne:
array = [1, 2, 3]
array.map! { |i| i.to_s }
et vous pouvez utiliser un raccourci vraiment cool pour proc: (https://stackoverflow.com/a/1961118/2257912)
array = [1, 2, 3]
array.map!(&:to_s)
array.map (&: to_s) => tableau d'entiers dans un tableau de chaînes
array.map (&: to_i) => tableau de chaînes dans un tableau d'entiers
double possible de [Appliquer procédé à des éléments de réseau] (http://stackoverflow.com/questions/6496931/apply- method-to-array-elements) –