David_Hogan
David_Hogan

Reputation: 125

Ruby Variable coming back with [["variable"]]

I'm trying to test getting a variable from mysql using ruby however when I get the variable and display it in the console using puts it reads variable with no quotations etc however when I attempt to call the variable elsewhere eg username = "#{dev_test1}" I get an output like this [["variable called from database"]] I just want to get a variable I can use in a string that doesn't haven [[""]] in it. The code I am using is below

require "mysql2"

    client = Mysql2::Client.new(:host => "localhost", :username => "root", :password => "", :database =>"test")
    test_query1 = client.query("SELECT test1 FROM accounts LIMIT 1").each(:as => :array)
    dev_test1 = test_query1.each { | row | }
    puts dev_test1
    test_query2 = client.query("SELECT test2 FROM accounts LIMIT 1").each(:as => :array)
    dev_test2 = test_query2.each { | row | }
    puts dev_test2
    username = "#{dev_test1}"
    password = "#{dev_test2}"
    puts username
    puts password

Upvotes: 0

Views: 54

Answers (1)

KenneyE
KenneyE

Reputation: 363

There are a handful of things that could be cleaned up in your code, but I'll look at why you are getting two different answers in the terminal and in your actual code.
In Ruby, puts and #{variable} are not the same thing. puts will actually alter the value to be a readable string by stripping out the array, if it is passed an array. This removes the brackets.

String interpolation (#{variable}) is the equivalent of calling .to_s on your variable. This will convert the array to a string with the brackets intact. So by the time you call puts, password has been saved as a string, so puts will display it as is, brackets and all.

So

password = "#{array}" #==> "[[array_contents]]"
puts password  #==> "[[array_contents]]"

Whereas

puts array  #==> "array_contents"

Upvotes: 2

Related Questions