1

String他の Ruby ファイルで使用したいクラスでカスタム インスタンス メソッドを定義しました。ファイル(カスタムメソッドを定義したファイル)を-ingすることでそれを行うことができますがrequire、(必要なく)自然に使用したいですrequire

例: 「custom_string.rb」ファイルでこれを定義しました。

class String
  def set_style(style)
    puts "\n#{self}"
    self.size.times do
    print style
    end
  end
end

次に、set_style「test.rb」ファイルでメソッドを使用するには、次のようにする必要があります。

require 'custom_string'
puts "hello".set_style("*")

私は Rails プロジェクトを使用していません。私のファイルをデフォルトで (ruby コマンドラインから) ruby​​ にインクルードして、Ruby のすべてのファイルで利用できるようにする方法はありますか?

4

2 に答える 2

4

これが自動的に含まれるのを見つけられなかっrequire 'custom_string'た場合、別の場所、別のサーバーでプログラムを実行したり、github でコードを共有したりするとどうなりますか。コードは期待どおりに実行されなくなります。助けを求めるときに投稿した結果は、他の人々と一致しなくなります。Ruby の動作を追跡不可能な方法で変更するのは、悪い考えのように思えます。

irbこの動作が必要な場合は、 require を に追加できます~/.irbrc

コマンドラインに追加する@Haulethソリューションにより、動作の変更を追跡できます。.bashrcまたは他のシェル rc にエイリアスを追加して、デフォルトでこの動作を行うことができます。

于 2012-11-09T11:25:59.523 に答える
1

Ruby 1.9 ヘルプ:

$ ruby --help
Usage: ruby [switches] [--] [programfile] [arguments]
  -0[octal]       specify record separator (\0, if no argument)
  -a              autosplit mode with -n or -p (splits $_ into $F)
  -c              check syntax only
  -Cdirectory     cd to directory, before executing your script
  -d              set debugging flags (set $DEBUG to true)
  -e 'command'    one line of script. Several -e's allowed. Omit [programfile]
  -Eex[:in]       specify the default external and internal character encodings
  -Fpattern       split() pattern for autosplit (-a)
  -i[extension]   edit ARGV files in place (make backup if extension supplied)
  -Idirectory     specify $LOAD_PATH directory (may be used more than once)
  -l              enable line ending processing
  -n              assume 'while gets(); ... end' loop around your script
  -p              assume loop like -n but print line also like sed
  -rlibrary       require the library, before executing your script
  -s              enable some switch parsing for switches after script name
  -S              look for the script using PATH environment variable
  -T[level=1]     turn on tainting checks
  -v              print version number, then turn on verbose mode
  -w              turn warnings on for your script
  -W[level=2]     set warning level; 0=silence, 1=medium, 2=verbose
  -x[directory]   strip off text before #!ruby line and perhaps cd to directory
  --copyright     print the copyright
  --version       print the version

見てみましょう:

-rlibrary       require the library, before executing your script
于 2012-11-09T11:25:21.383 に答える