2017-09-20 8 views
1

문자열로 변환 된 활성 지원 시간 객체를 객체로 다시 변환하려면 어떻게해야합니까? 즉, 문자열에서 활성 지원 객체를 어떻게 찾을 수 있습니까?문자열의 활성 지원 timezone 객체를 다시 레일 객체로 변환

예 : 나는 그리고 to_s를 사용하여 문자열이 객체를 변환하면

a = ActiveSupport::TimeZone.all.first = 
#<ActiveSupport::TimeZone:0x007f8c45bc1848 @name="American Samoa", 
@tzinfo=#<TZInfo::TimezoneProxy: Pacific/Pago_Pago>, @utc_offset=nil> 

, 내가 얻을 "(GMT-11 : 00) 아메리칸 사모아".

"(GMT-11 : 00) 아메리칸 사모아"가있는 경우 어떻게 객체를 찾을 수 있습니까?

답변

1
# let 
timezone_string = '(GMT-11:00) American Samoa' 

# let's capture the "American Samoa" substring from above (as an example) 
matches = timezone_string.match /\(GMT.*?\) (.*)/ 
timezone_name = matches[1] 

# then we look up the corresponding Timezone object using the "American Samoa" timezone_name 
timezone = ActiveSupport::TimeZone[timezone_name] 
2

이 괄호의 첫 번째 쌍 사이의 모든 것을 제거하고 나머지 문자열을 사로 잡고 :

a = ActiveSupport::TimeZone.all.first.to_s.match(/\(.*?\) (.*)/)[1] 

을 ... 그리고 당신은 ActiveSupport::Timezone 개체를 찾을 수 있습니다

ActiveSupport::Timezone[a]

0

해답을 주셔서 감사합니다. 는 또한 나에게 이름을 부여하고 난

ActiveSupport::TimeZone[tz_value]. 
+0

오 없음을 사용하여 객체를 찾는하고있는이

tz_value = business_timezone.split(')').second.strip 

을 시도했다. 그러지 마. 이 "Mountain Time (US & Canada)"와 같은 문자열이있는 시간대가 있기 때문에; [here] (http://api.rubyonrails.org/v5.1/classes/ActiveSupport/TimeZone.html)를 참조하십시오. 이것은'tz_value'가 정확하지 않다는 것을 의미합니다. 내 답변은 실제로 [Rails 문서] (http://api.rubyonrails.org/v5.1/classes/ActiveSupport/TimeZone.html)에 따라 나온 것인데, 여기에서'to_s()'의 소스 코드를 보았습니다. 문자열에서 정확한 시간대. –

+0

오 고마워! 나는 그것을 통해 가서 그에 따라 내 코드를 수정합니다 :) –

+0

괜찮습니다! :) –