Search code examples
mysqlrubymysql2

Ruby / MySQL fetching single row but still using .each?


I'm using the MySQL2 Ruby driver - but it seems a bit redundant having to call

result.each{ |r| puts r['name'] }

for a single row of data that is returned. There must be a simpler way to get the mysql field I want without having to use the each block?


Solution

  • Your result should be a Mysql2::Result and that's Enumerable so you can use first (and the rest of the Enumerable goodies) on it:

    puts result.first['name']