-2

im making a program and i need to combine a lot of variables, most of them strings but i have some int, by doing this

name = "#{variable1}#{variable2}"
name2 = "#{variable2}#{variable1}"

it´s a simple example with just two variables but thats the idea, what im trying to make. i am doing all the possibilities one by one, even when is more than two variables but there are many combinations. Is there an easy way to do it or i have to do it one by one?Also, do i need to write the quotation marks separately or that way is fine?

marcos
  • 42
  • 8

3 Answers3

3

Is this what you had in mind?

variable1 = "cat"
variable2 = 9
variable3 = "lives"
arr = [variable1, variable2, variable3]
  #=> ["cat", 9, "lives"] 
arr.join    
  #=> "cat9lives"
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

Put all or some of these variables into an array which will produce the combinations easier.

s1 = 'a'
s2 = 'b'
s3 = 'c'
 n = 8
[s1, s2, s3, n].combination(3).map(&:join)
=> ["abc", "ab8", "ac8", "bc8"]

Above example assumes that you will pick any of 3 variables from the array and calculate the combinations. You may want to adjust that number to meet your needs.

0

The whole idea of programming is not doing all possibilities one by one. "there are many combinations": they look like permutations to me. If that is the case:

var1 = "aa"
var2 = "bb"
var3 = 2

res = [var1, var2, var3].permutation.map{|perm| perm.join}
p res #=> ["aabb2", "aa2bb", "bbaa2", "bb2aa", "2aabb", "2bbaa"]
steenslag
  • 79,051
  • 16
  • 138
  • 171