Search code examples
rubyvariablesoperation

Operations inside variable bookmark = [(1).times {puts "<||>"}]


bookmark = [(10).times {print "<||>"}]

puts "\n#{bookmark}"

This is what I can see when printing this variable.

$
<||><||><||><||><||><||><||><||><||><||>

[10]

How could I do that this will be printing the correct operation inside of the variable bookmark

Edited: Let's change the number of times to 10. I will like to be able to use the result of that variable any time that I recall it

Thank you.


Solution

  • So what you're doing when you do this:

    bookmark = [(10).times {print "<||>"}]
    puts "\n#{bookmark}"
    

    Is you are creating a variable named bookmark. Then you are setting it to an array, with one element. Te element is: (10).times {print "<||>"}. What that does is take the integer 10, and then loops 10 times and prints <||>. It then returns itself which is the integer 10. If you want an array with ten values, each of them being "<||>", then you need to do something a little bit different.

    You can multiply arrays by an integer to increase the amount of the elements you multiplied.

    bookmark = ["<||>"] * 10 will set bookmark to ["<||>", "<||>", "<||>", "<||>", "<||>", "<||>", "<||>", "<||>", "<||>", "<||>"]. If when you puts "#{bookmark}" you want each of those elements to be on it's own line, you shouldn't add a newline in front (\n), but you can join the array to form a string, and you can separate each element with a newline: puts bookmark.join("\n").