[ruby-list:50803] Re: [質問] メソッド内で、クラス new するのは良くない?

From: masayoshi takahashi <maki@...>
Date: 2019-07-03 14:35:11 UTC
List: ruby-list #50803
高橋征義です。

2019年7月3日(水) 12:29 <yamataka@u08.itscom.net>:
> REXML::Document.new
> https://docs.ruby-lang.org/ja/latest/method/REXML=3a=3aDocument/s/new.html
> のマニュアルをみたところ,
>
> singleton method
>
> との記載より、インスタンスがそもそも1つのみで、
> 問題ないとの認識に至りました。

いえ、そのsingleton methodは「インスタンスがそもそも1つのみ」という意味ではないのでした。
言ってみれば「1つしかないREXML::Documentクラスオブジェクト」自体のメソッドなのでsingleton method、
といったような意味です。
(クラスメソッドと呼ばれているメソッドが、ここでのsingleton methodに該当します)

元々の質問については、具体的な状況がわからないのでなんともなのですが、

> doc = REXML::Document.new(xml)

のxmlが毎回違う内容であれば特に問題ないかと思いますし、
毎回同じ内容で、変更もしないのであれば、docを@docにして使い回すようにした方がよいかもしれません。




> > ■ 自作コード(抜粋)
> >
> > require 'rexml/document'
> >
> > def get_text_from_page_source_xml(**resource_ids)
> >
> >   xml = @cbelement.page_source
> >   doc = REXML::Document.new(xml)
> >
> >   resource_ids.each do |rid,v|
> >     arid  = "com.aspiro.tidal:id/" + rid.to_s # arid: actual resource id
> >     xpath = "//*[@resource-id='#{arid}']" # need ' at before and end #{id}
> >
> >     begin
> >       text = doc.elements[xpath].attributes["text"]
> >       resource_ids[rid] = text
> >     rescue => e
> >       resource_ids[rid] = nil
> >     end
> >   end
> >
> >   return resource_ids
> > end
> >
> > id0 = :artistName
> > id1 = :mediaItemTitle
> > texts = get_text_from_page_source_xml(id0 => :nil, id1 => :nil)
> >

In This Thread