ファイル"A.txt"
がテキストの単一の行(または、この行がファイルから抽出される)を含むと仮定:
s1 = 'This is a sentence with a #{my_var}'
及び第二のファイル、"Iamascript.rb"
、含ま:
s2 =<<_
line of code
line of code
my_var = "period"
line of code
line of code
_
#=> "line of code\n line of code\n my_var = 'period'\n line of code\nline of code\n"
を
これらのファイルを作成しましょう:
File.write("A.txt", s1)
#=> 35
File.write("Iamascript.rb", s2)
#=> 78
"A.txt"
の最初の行を読み取って、"\#{"
で始まり"}"
で終わる文字列を抽出し、その文字列から変数名を抽出します。
r1 =/
\#\{ # match characters
[_a-z]+ # match > 0 understores or lower case letters
\} # match character
/x # free-spacing regex definition mode
s1 = File.read("A.txt")
#=> "This is a sentence with a #{my_var}"
match = s1[r1]
#=> "\#{my_var}"
var_name = match[2..-2]
#=> "my_var"
"Iamascript.rb"を読み、次の正規表現に一致する行を探します。
r2 =/
\A # match beginning of string
#{var_name} # value of var_name
\s*=\s* # match '=' and surrounding whitespace
([\"']) # match a single or double quote in capture group 1
([^\"']+) # match other than single or double quote in capture group 2
([\"']) # match a single or double quote in capture group 3
\z # match end of string
/x # free-spacing regex definition mode
#=>/
# \A # match beginning of string
# my_var # value of var_name
# \s*=\s* # match '=' and surrounding whitespace
# ([\"']) # match a single or double quote in capture group 1
# ([^\"']+) # match other than single or double quote in capture group 2
# ([\"']) # match a single or double quote in capture group 3
# \z # match end of string
# /x
一致が見つかった場合は、テキスト置換、他のリターンnil
で"A.txt"
から行を返します。
if File.foreach("Iamascript.rb").find { |line| line.strip =~ r2 && $1==$3 }
str.sub(match, $2)
else
nil
end
#=> "This is a sentence with a period"
ありがとう、これは私の魅力のように動作します。外部の.txtまたは.rbファイルからハッシュを読み込み、そのキー(および値)を「メイン」コードでこれを使用することも可能ですか? – Phero
動作のない純粋なデータを読みたい場合は、プログラミング言語ではなく純粋なデータ記述言語を使用する方がはるかに優れています(より簡単で*安全です)。 (そして、結局のところ、ERbはあなたのすべてのデータを削除するコード、あなたのハードディスクをフォーマットする、バックドアを開始するコードなど、任意の* Rubyコードを埋め込むことができます) XML、YAML、JSONなどのデータ言語を使用します。 (XMLではなく、JSONやYAMLを好むでしょう。観客、つまりそのファイルを編集しなければならない人々に依存します。) –
プロジェクトは純粋なデータ抽出に関するものではなく、テンプレートを使用するのは便利です。私はちょうどいくつかのコードに複数の(異なる)出力を持ち、すべてをコード化しなくてもテンプレートを使用するというアイディアが好きです。しかし、セキュリティ上の懸念があると言えば、毎回自分のコードを変更するでしょう。 – Phero