Question

My hash looks like:

{:system=>"rr1k1"}

If I do:

puts @var[:system]

It looks like:

systemrr1k1

How do I just get rr1k1 without doing a @var.each ?

EDIT:

In response to comments below. My actual variable is set from a db query with sequel that only has one result. When I just do a puts on the variable, it looks like:

puts @var
#<Sequel::MySQL::Dataset: "select distinct lower(system) as system from client where db = 'CLIENTDB1'">

And if I do a loop on it, I get:

@var.each do |x|
    p x
end

Gives me:

{:system=>"rr1k1"}

but puts @var[:system] gives me

systemrr1k1
Was it helpful?

Solution

You have a Sequel::MySQL::Dataset in @var, you can see that from the puts @var output. Sequel::MySQL::Dataset gets its [] method from Sequel::Dateset and that method:

- (Object) [](*conditions)

Returns the first record matching the conditions. Examples:

DB[:table][:id=>1] # SELECT * FROM table WHERE (id = 1) LIMIT 1
# => {:id=1}

That means that @var[:system] will give you a row, not a single value.

Perhaps you really want:

puts @var.first[:system]

to peel off the first (and only) row in the result set and then pull the :system value out of that single row.

OTHER TIPS

Your @var is a Sequel Dataset, which is an Enumerable. To access your data you'll have to reference the row or use .first like so:

puts @var[0][:system] # "rr1k1"

puts @var.first[:system]  # "rr1k1"

Since it is a Dataset there may be other rows so if you want to properly loop over every result you'll have to use .each.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top