2012-11-09 40 views
1

我在String类中定义了一个自定义实例方法,我想在其他ruby文件中使用它。我可以通过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中的所有文件?

回答

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 
+0

我不认为这是OP想要的。如果OP不介意每次输入'-rlibrary ...',那么OP就不会问这样的问题。 – sawa

+0

这个答案本身并不是问题的完整答案,但如果你建议定义一个终端命令来调用它,那么这可能是一个完整的答案。 – sawa

+0

非常感谢您的回答以及您的所有意见和讨论。 尽我所能,我认为这是实现我想要的最安全的方式。它可以在命令行中正常工作(我不介意每次输入一个标志),甚至在IDE中(例如RubyMine),我可以选择通过将标志添加到'Ruby Arguments'中来配置控制台,领域。所以从整体角度来看,我非常喜欢这个答案,并且非常感谢Hauleth。 – Mahab

4

如果你不这样做require 'custom_string'却发现离开这个被自动包含,当你运行你的程序发生了什么另一个位置,不同的服务器,在github上共享代码等。代码将不再按预期执行。您寻求帮助时发布的结果将不再与其他人相匹配。这听起来像是一个坏主意,在一个难以追踪的庄园中改变Ruby的行为。

如果你只是想irb有这种行为,那么你可以将需求添加到您的~/.irbrc

@Hauleth添加命令行的解决方案允许跟踪行为的变化。一个别名可以被添加到.bashrc或其他shell rc默认情况下给这种行为。

+0

我认为对于OP是否被追踪至关重要。 OP似乎只想保存输入。 – sawa

+1

这会不会导致以后难以找到问题? – Morgan

+0

@Munkymorgy伟大的一点!非常感谢您的建议和答复。非常感谢。 – Mahab