ruby middleman hash traversal

69 views Asked by At

New to hashes. I've got a hash from middleman data file which is automatically generated by contentful_middleman. Basically

data.space.homepage = {
  "PCWLCTeTCKsaoGGSQOc6i"=>{
    "id"=>"PCWLCTeTCKsaoGGSQOc6i",
    "pageTitle"=>"Page Title",
    "pageContent"=>"page content",
  }
}

Because PCWLCTeTCKsaoGGSQOc6i is automatically generated I have to be able to reference it without using this key.

I don't know why exactly but the underscore here gets me where I need to be:

        <% data.space.homepage.each do |_, item| %>
          <h1 class="tag"><%= item.pageTitle %></h1>
        <% end %>

I'd like to be able to access pageTitle and pageContent without looping over the data but I can't figure out if that's possible without explicitly using the key PCWLCTeTCKsaoGGSQOc6i

1

There are 1 answers

1
Eric Duminil On BEST ANSWER

If homepage is a hash with a single pair of key/value, you can use :

title, content = data.space.homepage.values.first.values_at('pageTitle', 'pageContent')
title   #=> "Page Title"
content #=> "page content"

The id is :

homepage.keys.first #=> "PCWLCTeTCKsaoGGSQOc6i"