本文介绍了Ruby on Rails字符串转OpenStruct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下OpenStruct对象,但是如果我对它调用.class,则它是一个字符串.如何将其重新变成OpenStruct对象?

I have the following OpenStruct object but if I call .class on it is a string. How do I turn it back into a OpenStruct object?

[
 #<OpenStruct source="hkepc.com", visits="8", visitBounceRate="37.5", avgTimeOnSite="199.375", pageviews="25", pageviewsPerVisit="3.125">, 
 #<OpenStruct source="1st-tag.co.uk", visits="6", visitBounceRate="100.0", avgTimeOnSite="0.0", pageviews="6", pageviewsPerVisit="1.0">, 
 #<OpenStruct source="facebook.com", visits="5", visitBounceRate="80.0", avgTimeOnSite="8.2", pageviews="6", pageviewsPerVisit="1.2">
]

推荐答案

有点棘手,但我认为可以实现您的目标:

A little bit hacky, but I think achieves your goal:

require 'ostruct'

string_array = '[
 #<OpenStruct source="hkepc.com", visits="8", visitBounceRate="37.5", avgTimeOnSite="199.375", pageviews="25", pageviewsPerVisit="3.125">, 
 #<OpenStruct source="1st-tag.co.uk", visits="6", visitBounceRate="100.0", avgTimeOnSite="0.0", pageviews="6", pageviewsPerVisit="1.0">, 
 #<OpenStruct source="facebook.com", visits="5", visitBounceRate="80.0", avgTimeOnSite="8.2", pageviews="6", pageviewsPerVisit="1.2">
]'

string_array.gsub(/(\n|#<OpenStruct|\[|\]|\s+)/, '').split('>,').map do |attrs|
  struct_attrs = attrs.split(',')
  attrs = struct_attrs.inject({}) do |hash, elem|
    hash[elem.split('=').first] = elem.split('=').last.gsub('"', '')
    hash
  end

  OpenStruct.new(attrs)
end

这篇关于Ruby on Rails字符串转OpenStruct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 05:01