Reputation: 768
I am attempting to access hash data in sinatra:
require 'rubygems'
require 'sinatra'
class List
def self.items
return items = {
:something1 => { :attribute1 => "somestring1", :attribute2 => "somestring2" },
:something2 => { :attribute1 => "somestring3", :attribute2 => "somestring4" }
}
end
end
list = List.items
get '/' do
list.each do |name, meta|
"#{name}<br>#{meta[:attribute1]}<br>#{meta[:attribute2]}<br><br>"
end
end
I expected sinatra to print the hash data of each hash. However, it printed just the hashes instead (probably because I called list.each
). The console prints the expected result when I use puts
.
To clarify, the desired result is:
something1
somestring1
somestring2
something2
somestring3
somestring4
How do I make sinatra print just the variables?
Thanks!
Upvotes: 1
Views: 1126
Reputation: 15802
Use map
instead of each
, and then join the result to return a string:
get '/' do
list.map do |name, meta|
"#{name}<br>#{meta[:attribute1]}<br>#{meta[:attribute2]}<br><br>"
end.join
end
each
returns the array you call it on. map
will return a new array, transforming each entry in the Enumerable according to your block.
Upvotes: 2
Reputation: 1764
Try this:
get '/' do
s = ''
list.each do |name, meta|
s << "#{name}<br>#{meta[:attribute1]}<br>#{meta[:attribute2]}<br><br>"
end
return s
end
Upvotes: 4