- #
- C
- D
- R
- #
- A
- B
- C
- D
- E
- F
- G
- H
- I
- K
- L
- M
- N
- O
- P
- R
- S
- T
- U
- V
- W
| RUBY_VERSION | = | v |
| RUBY_RELEASE_DATE | = | d |
| RUBY_PLATFORM | = | p |
| RUBY_PATCHLEVEL | = | INT2FIX(RUBY_PATCHLEVEL) |
| RUBY_DESCRIPTION | = | tmp |
| RUBY_COPYRIGHT | = | tmp |
| VERSION | = | v |
obsolete constants |
||
| RELEASE_DATE | = | d |
| PLATFORM | = | p |
| MatchingData | = | rb_cMatch |
| STDIN | = | rb_stdin |
constants to hold original stdin/stdout/stderr |
||
| STDOUT | = | rb_stdout |
| STDERR | = | rb_stderr |
| ARGF | = | argf |
| ENV | = | envtbl |
| ENV | = | envtbl |
| NIL | = | Qnil |
| TRUE | = | Qtrue |
| FALSE | = | Qfalse |
| TOPLEVEL_BINDING | = | rb_f_binding(ruby_top_self) |
| DATA | = | f |
| ARGV | = | rb_argv |
| IPsocket | = | rb_cIPSocket |
| TCPsocket | = | rb_cTCPSocket |
| SOCKSsocket | = | rb_cSOCKSSocket |
| TCPserver | = | rb_cTCPServer |
| UDPsocket | = | rb_cUDPSocket |
| UNIXsocket | = | rb_cUNIXSocket |
| UNIXserver | = | rb_cUNIXServer |
See accept.
Source: show
# File lib/optparse.rb, line 828 828: def self.accept(*args, &blk) top.accept(*args, &blk) end
See getopts.
Source: show
# File lib/optparse.rb, line 1407 1407: def self.getopts(*args) 1408: new.getopts(*args) 1409: end
Returns an incremented value of default according to arg.
Source: show
# File lib/optparse.rb, line 764 764: def self.inc(arg, default = nil) 765: case arg 766: when Integer 767: arg.nonzero? 768: when nil 769: default.to_i + 1 770: end 771: end
Initializes the instance and yields itself if called with a block.
| banner: | Banner message. |
| width: | Summary width. |
| indent: | Summary indent. |
Source: show
# File lib/optparse.rb, line 783 783: def initialize(banner = nil, width = 32, indent = ' ' * 4) 784: @stack = [DefaultList, List.new, List.new] 785: @program_name = nil 786: @banner = banner 787: @summary_width = width 788: @summary_indent = indent 789: @default_argv = ARGV 790: add_officious 791: yield self if block_given? 792: end
Source: show
# File ext/extmk.rb, line 451 451: def initializeinitializeinitialize(src) 452: super("#{src}.c", "#{src}.#{$OBJEXT}") 453: end
See reject.
Source: show
# File lib/optparse.rb, line 841 841: def self.reject(*args, &blk) top.reject(*args, &blk) end
Source: show
# File lib/optparse.rb, line 808 808: def self.terminate(arg = nil) 809: throw :terminate, arg 810: end
Source: show
# File lib/optparse.rb, line 813 813: def self.top() DefaultList end
Initializes a new instance and evaluates the optional block in context of the instance. Arguments args are passed to new, see there for description of parameters.
This method is deprecated, its behavior corresponds to the older new method.
Source: show
# File lib/optparse.rb, line 755 755: def self.with(*args, &block) 756: opts = new(*args) 757: opts.instance_eval(&block) 758: opts 759: end
Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning.
Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).
The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:
1 == 1.0 #=> true 1.eql? 1.0 #=> false
Source: show
static VALUE
rb_obj_equal(obj1, obj2)
VALUE obj1, obj2;
{
if (obj1 == obj2) return Qtrue;
return Qfalse;
}
Case Equality—For class Object, effectively the same as calling #==, but typically overridden by descendents to provide meaningful semantics in case statements.
Source: show
VALUE
rb_equal(obj1, obj2)
VALUE obj1, obj2;
{
VALUE result;
if (obj1 == obj2) return Qtrue;
result = rb_funcall(obj1, id_eq, 1, obj2);
if (RTEST(result)) return Qtrue;
return Qfalse;
}
Pattern Match—Overridden by descendents (notably Regexp and String) to provide meaningful pattern-match semantics.
Source: show
static VALUE
rb_obj_pattern_match(obj1, obj2)
VALUE obj1, obj2;
{
return Qfalse;
}
Source: show
# File lib/complex.rb, line 90 90: def Complex(a, b = 0) 91: if b == 0 and (a.kind_of?(Complex) or defined? Complex::Unify) 92: a 93: else 94: Complex.new( a.real-b.imag, a.imag+b.real ) 95: end 96: end
The primary interface to this library. Use to setup delegation when defining your class.
class MyClass < DelegateClass( ClassToDelegateTo ) # Step 1
def initialize
super(obj_of_ClassToDelegateTo) # Step 2
end
end
Source: show
# File lib/delegate.rb, line 259 259: def DelegateClass(superclass) 260: klass = Class.new 261: methods = superclass.public_instance_methods(true) 262: methods -= ::Kernel.public_instance_methods(false) 263: methods |= ["to_s","to_a","inspect","==","=~","==="] 264: klass.module_eval { 265: def initialize(obj) # :nodoc: 266: @_dc_obj = obj 267: end 268: def method_missing(m, *args) # :nodoc: 269: unless @_dc_obj.respond_to?(m) 270: super(m, *args) 271: end 272: @_dc_obj.__send__(m, *args) 273: end 274: def respond_to?(m, include_private = false) # :nodoc: 275: return true if super 276: return @_dc_obj.respond_to?(m, include_private) 277: end 278: def __getobj__ # :nodoc: 279: @_dc_obj 280: end 281: def __setobj__(obj) # :nodoc: 282: raise ArgumentError, "cannot delegate to self" if self.equal?(obj) 283: @_dc_obj = obj 284: end 285: def clone # :nodoc: 286: new = super 287: new.__setobj__(__getobj__.clone) 288: new 289: end 290: def dup # :nodoc: 291: new = super 292: new.__setobj__(__getobj__.clone) 293: new 294: end 295: } 296: for method in methods 297: begin 298: klass.module_eval "def \#{method}(*args, &block)\nbegin\n@_dc_obj.__send__(:\#{method}, *args, &block)\nensure\n$@.delete_if{|s| ::Delegator::IgnoreBacktracePat =~ s} if $@\nend\nend\n", __FILE__, __LINE__+1 299: rescue SyntaxError 300: raise NameError, "invalid identifier %s" % method, caller(3) 301: end 302: end 303: return klass 304: end
Source: show
# File ext/digest/lib/digest.rb, line 48 48: def Digest(name) 49: Digest.const_get(name) 50: end
Creates a Rational number (i.e. a fraction). a and b should be Integers:
Rational(1,3) # -> 1/3
Note: trying to construct a Rational with floating point or real values produces errors:
Rational(1.1, 2.3) # -> NoMethodError
Source: show
# File lib/rational.rb, line 31 31: def Rational(a, b = 1) 32: if a.kind_of?(Rational) && b == 1 33: a 34: else 35: Rational.reduce(a, b) 36: end 37: end
Document-method: object_id
Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id. Object#object_id is a different concept from the :name notation, which returns the symbol id of name. Replaces the deprecated Object#id.
Source: show
VALUE
rb_obj_id(VALUE obj)
{
/*
* 32-bit VALUE space
* MSB ------------------------ LSB
* false 00000000000000000000000000000000
* true 00000000000000000000000000000010
* nil 00000000000000000000000000000100
* undef 00000000000000000000000000000110
* symbol ssssssssssssssssssssssss00001110
* object oooooooooooooooooooooooooooooo00 = 0 (mod sizeof(RVALUE))
* fixnum fffffffffffffffffffffffffffffff1
*
* object_id space
* LSB
* false 00000000000000000000000000000000
* true 00000000000000000000000000000010
* nil 00000000000000000000000000000100
* undef 00000000000000000000000000000110
* symbol 000SSSSSSSSSSSSSSSSSSSSSSSSSSS0 S...S % A = 4 (S...S = s...s * A + 4)
* object oooooooooooooooooooooooooooooo0 o...o % A = 0
* fixnum fffffffffffffffffffffffffffffff1 bignum if required
*
* where A = sizeof(RVALUE)/4
*
* sizeof(RVALUE) is
* 20 if 32-bit, double is 4-byte aligned
* 24 if 32-bit, double is 8-byte aligned
* 40 if 64-bit
*/
if (TYPE(obj) == T_SYMBOL) {
return (SYM2ID(obj) * sizeof(RVALUE) + (4 << 2)) | FIXNUM_FLAG;
}
if (SPECIAL_CONST_P(obj)) {
return LONG2NUM((long)obj);
}
return (VALUE)((long)obj|FIXNUM_FLAG);
}
Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.
class Klass
def hello(*args)
"Hello " + args.join(' ')
end
end
k = Klass.new
k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
Source: show
static VALUE
rb_f_send(argc, argv, recv)
int argc;
VALUE *argv;
VALUE recv;
{
VALUE vid;
if (argc == 0) rb_raise(rb_eArgError, "no method name given");
vid = *argv++; argc--;
PUSH_ITER(rb_block_given_p()?ITER_PRE:ITER_NOT);
vid = rb_call(CLASS_OF(recv), recv, rb_to_id(vid), argc, argv, 1, Qundef);
POP_ITER();
return vid;
}
Source: show
# File lib/optparse.rb, line 922 922: def abort(mesg = $!) 923: super("#{program_name}: #{mesg}") 924: end
Directs to accept specified class t. The argument string is passed to the block in which it should be converted to the desired class.
| t: | Argument class specifier, any object including Class. |
| pat: | Pattern for argument, defaults to t if it responds to match. |
accept(t, pat, &block)
Source: show
# File lib/optparse.rb, line 824 824: def accept(*args, &blk) top.accept(*args, &blk) end
Source: show
# File ext/dl/test/test.rb, line 9 9: def assert(label, ty, *conds) 10: $TOTAL += 1 11: cond = !conds.include?(false) 12: if( cond ) 13: printf("succeed in `#{label}'\n") 14: else 15: $FAIL += 1 16: case ty 17: when :may 18: printf("fail in `#{label}' ... expected\n") 19: when :must 20: printf("fail in `#{label}' ... unexpected\n") 21: when :raise 22: raise(RuntimeError, "fail in `#{label}'") 23: end 24: end 25: end
Heading banner preceding summary.
Source: show
# File lib/optparse.rb, line 866 866: def banner 867: unless @banner 868: @banner = "Usage: #{program_name} [options]" 869: visit(:add_banner, @banner) 870: end 871: @banner 872: end
Subject of on_tail.
Source: show
# File lib/optparse.rb, line 936 936: def base 937: @stack[1] 938: end
Returns the size of the given type. You may optionally specify additional headers to search in for the type.
If found, a macro is passed as a preprocessor constant to the compiler using the type name, in uppercase, prepended with ‘SIZEOF_’, followed by the type name, followed by ’=X’ where ‘X’ is the actual size.
For example, if check_sizeof(‘mystruct’) returned 12, then the SIZEOF_MYSTRUCT=12 preprocessor macro would be passed to the compiler.
Source: show
# File lib/mkmf.rb, line 922 922: def check_sizeof(type, headers = nil, &b) 923: expr = "sizeof(#{type})" 924: fmt = "%d" 925: def fmt.%(x) 926: x ? super : "failed" 927: end 928: checking_for checking_message("size of #{type}", headers), fmt do 929: if size = try_constant(expr, headers, &b) 930: $defs.push(format("-DSIZEOF_%s=%d", type.tr_cpp, size)) 931: size 932: end 933: end 934: end
Change the mode of each FILE to OCTAL-MODE.
ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE -v verbose
Source: show
# File lib/un.rb, line 195 195: def chmod 196: setup do |argv, options| 197: mode = argv.shift.oct 198: FileUtils.chmod mode, argv, options 199: end 200: end
Returns the class of obj, now preferred over Object#type, as an object’s type in Ruby is only loosely tied to that object’s class. This method must always be called with an explicit receiver, as class is also a reserved word in Ruby.
1.class #=> Fixnum self.class #=> Object
Source: show
VALUE
rb_obj_class(obj)
VALUE obj;
{
return rb_class_real(CLASS_OF(obj));
}
Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. Copies the frozen and tainted state of obj. See also the discussion under Object#dup.
class Klass
attr_accessor :str
end
s1 = Klass.new #=> #<Klass:0x401b3a38>
s1.str = "Hello" #=> "Hello"
s2 = s1.clone #=> #<Klass:0x401b3998 @str="Hello">
s2.str[1,4] = "i" #=> "i"
s1.inspect #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
s2.inspect #=> "#<Klass:0x401b3998 @str=\"Hi\">"
This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.
Source: show
VALUE
rb_obj_clone(obj)
VALUE obj;
{
VALUE clone;
if (rb_special_const_p(obj)) {
rb_raise(rb_eTypeError, "can't clone %s", rb_obj_classname(obj));
}
clone = rb_obj_alloc(rb_obj_class(obj));
RBASIC(clone)->klass = rb_singleton_class_clone(obj);
RBASIC(clone)->flags = (RBASIC(obj)->flags | FL_TEST(clone, FL_TAINT)) & ~(FL_FREEZE|FL_FINALIZE);
init_copy(clone, obj);
RBASIC(clone)->flags |= RBASIC(obj)->flags & FL_FREEZE;
return clone;
}
Source: show
# File ext/extmk.rb, line 245 245: def compiled?(target) 246: $compiled[target] 247: end
Completes shortened long style option switch and returns pair of canonical switch and switch descriptor OptionParser::Switch.
| id: | Searching table. |
| opt: | Searching key. |
| icase: | Search case insensitive if true. |
| pat: | Optional pattern for completion. |
Source: show
# File lib/optparse.rb, line 1444 1444: def complete(typ, opt, icase = false, *pat) 1445: if pat.empty? 1446: search(typ, opt) {|sw| return [sw, opt]} # exact match or... 1447: end 1448: raise AmbiguousOption, catch(:ambiguous) { 1449: visit(:complete, typ, opt, icase, *pat) {|opt, *sw| return sw} 1450: raise InvalidOption, opt 1451: } 1452: end
Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY
ruby -run -e cp -- [OPTION] SOURCE DEST -p preserve file attributes if possible -r copy recursively -v verbose
Source: show
# File lib/un.rb, line 68 68: def cp 69: setup("pr") do |argv, options| 70: cmd = "cp" 71: cmd += "_r" if options.delete :r 72: options[:preserve] = true if options.delete :p 73: dest = argv.pop 74: argv = argv[0] if argv.size == 1 75: FileUtils.send cmd, argv, dest, options 76: end 77: end
Generates a header file consisting of the various macro definitions generated by other methods such as have_func and have_header. These are then wrapped in a custom ifndef based on the header file name, which defaults to ‘extconf.h’.
For example:
# extconf.rb
require 'mkmf'
have_func('realpath')
have_header('sys/utime.h')
create_header
create_makefile('foo')
The above script would generate the following extconf.h file:
#ifndef EXTCONF_H #define EXTCONF_H #define HAVE_REALPATH 1 #define HAVE_SYS_UTIME_H 1 #endif
Given that the create_header method generates a file based on definitions set earlier in your extconf.rb file, you will probably want to make this one of the last methods you call in your script.
Source: show
# File lib/mkmf.rb, line 1132 1132: def create_header(header = "extconf.h") 1133: message "creating %s\n", header 1134: sym = header.tr("a-z./\055", "A-Z___") 1135: hdr = ["#ifndef #{sym}\n#define #{sym}\n"] 1136: for line in $defs 1137: case line 1138: when /^-D([^=]+)(?:=(.*))?/ 1139: hdr << "#define #$1 #{$2 ? Shellwords.shellwords($2)[0] : 1}\n" 1140: when /^-U(.*)/ 1141: hdr << "#undef #$1\n" 1142: end 1143: end 1144: hdr << "#endif\n" 1145: hdr = hdr.join 1146: unless (IO.read(header) == hdr rescue false) 1147: open(header, "w") do |hfile| 1148: hfile.write(hdr) 1149: end 1150: end 1151: $extconf_h = header 1152: end
Generates the Makefile for your extension, passing along any options and preprocessor constants that you may have generated through other methods.
The target name should correspond the name of the global function name defined within your C extension, minus the ‘Init_’. For example, if your C extension is defined as ‘Init_foo’, then your target would simply be ‘foo’.
If any ’/’ characters are present in the target name, only the last name is interpreted as the target name, and the rest are considered toplevel directory names, and the generated Makefile will be altered accordingly to follow that directory structure.
For example, if you pass ‘test/foo’ as a target name, your extension will be installed under the ‘test’ directory. This means that in order to load the file within a Ruby program later, that directory structure will have to be followed, e.g. “require ‘test/foo’”.
The srcprefix should be used when your source files are not in the same directory as your build script. This will not only eliminate the need for you to manually copy the source files into the same directory as your build script, but it also sets the proper target_prefix in the generated Makefile.
Setting the target_prefix will, in turn, install the generated binary in a directory under your Config::CONFIG[‘sitearchdir’] that mimics your local filesystem when you run ‘make install’.
For example, given the following file tree:
ext/
extconf.rb
test/
foo.c
And given the following code:
create_makefile('test/foo', 'test')
That will set the target_prefix in the generated Makefile to ‘test’. That, in turn, will create the following file tree when installed via the ‘make install’ command:
/path/to/ruby/sitearchdir/test/foo.so
It is recommended that you use this approach to generate your makefiles, instead of copying files around manually, because some third party libraries may depend on the target_prefix being set properly.
The srcprefix argument can be used to override the default source directory, i.e. the current directory . It is included as part of the VPATH and added to the list of INCFLAGS.
Source: show
# File lib/mkmf.rb, line 1435 1435: def create_makefile(target, srcprefix = nil) 1436: $target = target 1437: libpath = $DEFLIBPATH|$LIBPATH 1438: message "creating Makefile\n" 1439: rm_f "conftest*" 1440: if CONFIG["DLEXT"] == $OBJEXT 1441: for lib in libs = $libs.split 1442: lib.sub!(/-l(.*)/, %%"lib\\1.#{$LIBEXT}"%) 1443: end 1444: $defs.push(format("-DEXTLIB='%s'", libs.join(","))) 1445: end 1446: 1447: if target.include?('/') 1448: target_prefix, target = File.split(target) 1449: target_prefix[0,0] = '/' 1450: else 1451: target_prefix = "" 1452: end 1453: 1454: srcprefix ||= '$(srcdir)' 1455: Config::expand(srcdir = srcprefix.dup) 1456: 1457: if not $objs 1458: $objs = [] 1459: srcs = Dir[File.join(srcdir, "*.{#{SRC_EXT.join(%q{,})}}")] 1460: for f in srcs 1461: obj = File.basename(f, ".*") << ".o" 1462: $objs.push(obj) unless $objs.index(obj) 1463: end 1464: elsif !(srcs = $srcs) 1465: srcs = $objs.collect {|obj| obj.sub(/\.o\z/, '.c')} 1466: end 1467: $srcs = srcs 1468: for i in $objs 1469: i.sub!(/\.o\z/, ".#{$OBJEXT}") 1470: end 1471: $objs = $objs.join(" ") 1472: 1473: target = nil if $objs == "" 1474: 1475: if target and EXPORT_PREFIX 1476: if File.exist?(File.join(srcdir, target + '.def')) 1477: deffile = "$(srcdir)/$(TARGET).def" 1478: unless EXPORT_PREFIX.empty? 1479: makedef = %{-pe "sub!(/^(?=\\w)/,'#{EXPORT_PREFIX}') unless 1../^EXPORTS$/i"} 1480: end 1481: else 1482: makedef = %{-e "puts 'EXPORTS', '#{EXPORT_PREFIX}Init_$(TARGET)'"} 1483: end 1484: if makedef 1485: $distcleanfiles << '$(DEFFILE)' 1486: origdef = deffile 1487: deffile = "$(TARGET)-$(arch).def" 1488: end 1489: end 1490: origdef ||= '' 1491: 1492: libpath = libpathflag(libpath) 1493: 1494: dllib = target ? "$(TARGET).#{CONFIG['DLEXT']}" : "" 1495: staticlib = target ? "$(TARGET).#$LIBEXT" : "" 1496: mfile = open("Makefile", "wb") 1497: mfile.print configuration(srcprefix) 1498: mfile.print " 1499: libpath = #{($DEFLIBPATH|$LIBPATH).join(" ")} 1500: LIBPATH = #{libpath} 1501: DEFFILE = #{deffile} 1502: 1503: CLEANFILES = #{$cleanfiles.join(' ')} 1504: DISTCLEANFILES = #{$distcleanfiles.join(' ')} 1505: 1506: extout = #{$extout} 1507: extout_prefix = #{$extout_prefix} 1508: target_prefix = #{target_prefix} 1509: LOCAL_LIBS = #{$LOCAL_LIBS} 1510: LIBS = #{$LIBRUBYARG} #{$libs} #{$LIBS} 1511: SRCS = #{srcs.collect(&File.method(:basename)).join(' ')} 1512: OBJS = #{$objs} 1513: TARGET = #{target} 1514: DLLIB = #{dllib} 1515: EXTSTATIC = #{$static || ""} 1516: STATIC_LIB = #{staticlib unless $static.nil?} 1517: #{!$extout && defined?($installed_list) ? "INSTALLED_LIST = #{$installed_list}\n" : ""} 1518: " 1519: install_dirs.each {|d| mfile.print("%-14s= %s\n" % d) if /^[[:upper:]]/ =~ d[0]} 1520: n = ($extout ? '$(RUBYARCHDIR)/' : '') + '$(TARGET).' 1521: mfile.print " 1522: TARGET_SO = #{($extout ? '$(RUBYARCHDIR)/' : '')}$(DLLIB) 1523: CLEANLIBS = #{n}#{CONFIG['DLEXT']} #{n}il? #{n}tds #{n}map 1524: CLEANOBJS = *.#{$OBJEXT} *.#{$LIBEXT} *.s[ol] *.pdb *.exp *.bak 1525: 1526: all: #{$extout ? "install" : target ? "$(DLLIB)" : "Makefile"} 1527: static: $(STATIC_LIB)#{$extout ? " install-rb" : ""} 1528: " 1529: mfile.print CLEANINGS 1530: dirs = [] 1531: mfile.print "install: install-so install-rb\n\n" 1532: sodir = (dir = "$(RUBYARCHDIR)").dup 1533: mfile.print("install-so: ") 1534: if target 1535: f = "$(DLLIB)" 1536: dest = "#{dir}/#{f}" 1537: mfile.puts dir, "install-so: #{dest}" 1538: unless $extout 1539: mfile.print "#{dest}: #{f}\n" 1540: if (sep = config_string('BUILD_FILE_SEPARATOR')) 1541: f.gsub!("/", sep) 1542: dir.gsub!("/", sep) 1543: sep = ":/="+sep 1544: f.gsub!(/(\$\(\w+)(\))/) {$1+sep+$2} 1545: f.gsub!(/(\$\{\w+)(\})/) {$1+sep+$2} 1546: dir.gsub!(/(\$\(\w+)(\))/) {$1+sep+$2} 1547: dir.gsub!(/(\$\{\w+)(\})/) {$1+sep+$2} 1548: end 1549: mfile.print "\t$(INSTALL_PROG) #{f} #{dir}\n" 1550: if defined?($installed_list) 1551: mfile.print "\t@echo #{dir}/#{File.basename(f)}>>$(INSTALLED_LIST)\n" 1552: end 1553: end 1554: else 1555: mfile.puts "Makefile" 1556: end 1557: mfile.print("install-rb: pre-install-rb install-rb-default\n") 1558: mfile.print("install-rb-default: pre-install-rb-default\n") 1559: mfile.print("pre-install-rb: Makefile\n") 1560: mfile.print("pre-install-rb-default: Makefile\n") 1561: for sfx, i in [["-default", [["lib/**/*.rb", "$(RUBYLIBDIR)", "lib"]]], ["", $INSTALLFILES]] 1562: files = install_files(mfile, i, nil, srcprefix) or next 1563: for dir, *files in files 1564: unless dirs.include?(dir) 1565: dirs << dir 1566: mfile.print "pre-install-rb#{sfx}: #{dir}\n" 1567: end 1568: files.each do |f| 1569: dest = "#{dir}/#{File.basename(f)}" 1570: mfile.print("install-rb#{sfx}: #{dest}\n") 1571: mfile.print("#{dest}: #{f} #{dir}\n\t$(#{$extout ? 'COPY' : 'INSTALL_DATA'}) ") 1572: sep = config_string('BUILD_FILE_SEPARATOR') 1573: if sep 1574: f = f.gsub("/", sep) 1575: sep = ":/="+sep 1576: f = f.gsub(/(\$\(\w+)(\))/) {$1+sep+$2} 1577: f = f.gsub(/(\$\{\w+)(\})/) {$1+sep+$2} 1578: else 1579: sep = "" 1580: end 1581: mfile.print("#{f} $(@D#{sep})\n") 1582: if defined?($installed_list) and !$extout 1583: mfile.print("\t@echo #{dest}>>$(INSTALLED_LIST)\n") 1584: end 1585: end 1586: end 1587: end 1588: dirs.unshift(sodir) if target and !dirs.include?(sodir) 1589: dirs.each {|dir| mfile.print "#{dir}:\n\t$(MAKEDIRS) $@\n"} 1590: 1591: mfile.print "\nsite-install: site-install-so site-install-rb\nsite-install-so: install-so\nsite-install-rb: install-rb\n\n" 1592: 1593: return unless target 1594: 1595: mfile.puts SRC_EXT.collect {|ext| ".path.#{ext} = $(VPATH)"} if $nmake == ?b 1596: mfile.print ".SUFFIXES: .#{SRC_EXT.join(' .')} .#{$OBJEXT}\n" 1597: mfile.print "\n" 1598: 1599: CXX_EXT.each do |ext| 1600: COMPILE_RULES.each do |rule| 1601: mfile.printf(rule, ext, $OBJEXT) 1602: mfile.printf("\n\t%s\n\n", COMPILE_CXX) 1603: end 1604: end 1605: %w[c].each do |ext| 1606: COMPILE_RULES.each do |rule| 1607: mfile.printf(rule, ext, $OBJEXT) 1608: mfile.printf("\n\t%s\n\n", COMPILE_C) 1609: end 1610: end 1611: 1612: mfile.print "$(RUBYARCHDIR)/" if $extout 1613: mfile.print "$(DLLIB): " 1614: mfile.print "$(DEFFILE) " if makedef 1615: mfile.print "$(OBJS) Makefile\n" 1616: mfile.print "\t@-$(RM) $@\n" 1617: mfile.print "\t@-$(MAKEDIRS) $(@D)\n" if $extout 1618: link_so = LINK_SO.gsub(/^/, "\t") 1619: mfile.print link_so, "\n\n" 1620: unless $static.nil? 1621: mfile.print "$(STATIC_LIB): $(OBJS)\n\t" 1622: mfile.print "$(AR) #{config_string('ARFLAGS') || 'cru '}$@ $(OBJS)" 1623: config_string('RANLIB') do |ranlib| 1624: mfile.print "\n\t@-#{ranlib} $(DLLIB) 2> /dev/null || true" 1625: end 1626: end 1627: mfile.print "\n\n" 1628: if makedef 1629: mfile.print "$(DEFFILE): #{origdef}\n" 1630: mfile.print "\t$(RUBY) #{makedef} #{origdef} > $@\n\n" 1631: end 1632: 1633: depend = File.join(srcdir, "depend") 1634: if File.exist?(depend) 1635: suffixes = [] 1636: depout = [] 1637: open(depend, "r") do |dfile| 1638: mfile.printf "###\n" 1639: cont = implicit = nil 1640: impconv = proc do 1641: COMPILE_RULES.each {|rule| depout << (rule % implicit[0]) << implicit[1]} 1642: implicit = nil 1643: end 1644: ruleconv = proc do |line| 1645: if implicit 1646: if /\A\t/ =~ line 1647: implicit[1] << line 1648: next 1649: else 1650: impconv[] 1651: end 1652: end 1653: if m = /\A\.(\w+)\.(\w+)(?:\s*:)/.match(line) 1654: suffixes << m[1] << m[2] 1655: implicit = [[m[1], m[2]], [m.post_match]] 1656: next 1657: elsif RULE_SUBST and /\A(?!\s*\w+\s*=)[$\w][^#]*:/ =~ line 1658: line.gsub!(%r"(\s)(?!\.)([^$(){}+=:\s\/\\,]+)(?=\s|\z)") {$1 + RULE_SUBST % $2} 1659: end 1660: depout << line 1661: end 1662: while line = dfile.gets() 1663: line.gsub!(/\.o\b/, ".#{$OBJEXT}") 1664: line.gsub!(/\$\((?:hdr|top)dir\)\/config.h/, $config_h) if $config_h 1665: if /(?:^|[^\\])(?:\\\\)*\\$/ =~ line 1666: (cont ||= []) << line 1667: next 1668: elsif cont 1669: line = (cont << line).join 1670: cont = nil 1671: end 1672: ruleconv.call(line) 1673: end 1674: if cont 1675: ruleconv.call(cont.join) 1676: elsif implicit 1677: impconv.call 1678: end 1679: end 1680: unless suffixes.empty? 1681: mfile.print ".SUFFIXES: .", suffixes.uniq.join(" ."), "\n\n" 1682: end 1683: mfile.print "$(OBJS): $(RUBY_EXTCONF_H)\n\n" if $extconf_h 1684: mfile.print depout 1685: else 1686: headers = %w[ruby.h defines.h] 1687: if RULE_SUBST 1688: headers.each {|h| h.sub!(/.*/) {|*m| RULE_SUBST % m}} 1689: end 1690: headers << $config_h if $config_h 1691: headers << "$(RUBY_EXTCONF_H)" if $extconf_h 1692: mfile.print "$(OBJS): ", headers.join(' '), "\n" 1693: end 1694: 1695: $makefile_created = true 1696: ensure 1697: mfile.close if mfile 1698: end
Source: show
# File lib/rexml/xpath_parser.rb, line 8 8: def dclone 9: clone 10: end
Source: show
# File ext/dl/test/test.rb, line 27 27: def debug(*xs) 28: if( $DEBUG ) 29: xs.each{|x| 30: p x 31: } 32: end 33: end
Source: show
# File lib/optparse.rb, line 1183 1183: def define(*opts, &block) 1184: top.append(*(sw = make_switch(opts, block))) 1185: sw[0] 1186: end
Source: show
# File lib/optparse.rb, line 1198 1198: def define_head(*opts, &block) 1199: top.prepend(*(sw = make_switch(opts, block))) 1200: sw[0] 1201: end
Source: show
# File lib/optparse.rb, line 1212 1212: def define_tail(*opts, &block) 1213: base.append(*(sw = make_switch(opts, block))) 1214: sw[0] 1215: end
Sets a target name that the user can then use to configure various ‘with’ options with on the command line by using that name. For example, if the target is set to “foo”, then the user could use the —with-foo-dir command line option.
You may pass along additional ‘include’ or ‘lib’ defaults via the idefault and ldefault parameters, respectively.
Note that dir_config only adds to the list of places to search for libraries and include files. It does not link the libraries into your application.
Source: show
# File lib/mkmf.rb, line 1165 1165: def dir_config(target, idefault=nil, ldefault=nil) 1166: if dir = with_config(target + "-dir", (idefault unless ldefault)) 1167: defaults = Array === dir ? dir : dir.split(File::PATH_SEPARATOR) 1168: idefault = ldefault = nil 1169: end 1170: 1171: idir = with_config(target + "-include", idefault) 1172: $arg_config.last[1] ||= "${#{target}-dir}/include" 1173: ldir = with_config(target + "-lib", ldefault) 1174: $arg_config.last[1] ||= "${#{target}-dir}/lib" 1175: 1176: idirs = idir ? Array === idir ? idir : idir.split(File::PATH_SEPARATOR) : [] 1177: if defaults 1178: idirs.concat(defaults.collect {|dir| dir + "/include"}) 1179: idir = ([idir] + idirs).compact.join(File::PATH_SEPARATOR) 1180: end 1181: unless idirs.empty? 1182: idirs.collect! {|dir| "-I" + dir} 1183: idirs -= Shellwords.shellwords($CPPFLAGS) 1184: unless idirs.empty? 1185: $CPPFLAGS = (idirs.quote << $CPPFLAGS).join(" ") 1186: end 1187: end 1188: 1189: ldirs = ldir ? Array === ldir ? ldir : ldir.split(File::PATH_SEPARATOR) : [] 1190: if defaults 1191: ldirs.concat(defaults.collect {|dir| dir + "/lib"}) 1192: ldir = ([ldir] + ldirs).compact.join(File::PATH_SEPARATOR) 1193: end 1194: $LIBPATH = ldirs | $LIBPATH 1195: 1196: [idir, ldir] 1197: end
Prints obj on the given port (default $>). Equivalent to:
def display(port=$>)
port.write self
end
For example:
1.display "cat".display [ 4, 5, 6 ].display puts
produces:
1cat456
Source: show
static VALUE
rb_obj_display(argc, argv, self)
int argc;
VALUE *argv;
VALUE self;
{
VALUE out;
if (rb_scan_args(argc, argv, "01", &out) == 0) {
out = rb_stdout;
}
rb_io_write(out, self);
return Qnil;
}
Source: show
# File ext/dl/extconf.rb, line 98 98: def dlc_define(const) 99: $dlconfig_h << "#if !defined(#{const})\n" + 100: "# define #{const}\n" + 101: "#endif\n" 102: end
Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. See also the discussion under Object#clone. In general, clone and dup may have different semantics in descendent classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendent object to create the new instance.
This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.
Source: show
VALUE
rb_obj_dup(obj)
VALUE obj;
{
VALUE dup;
if (rb_special_const_p(obj)) {
rb_raise(rb_eTypeError, "can't dup %s", rb_obj_classname(obj));
}
dup = rb_obj_alloc(rb_obj_class(obj));
init_copy(dup, obj);
return dup;
}
Tests for the presence of an —enable-config or —disable-config option. Returns true if the enable option is given, false if the disable option is given, and the default value otherwise.
This can be useful for adding custom definitions, such as debug information.
Example:
if enable_config("debug")
$defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG"
end
Source: show
# File lib/mkmf.rb, line 1094 1094: def enable_config(config, *defaults) 1095: if arg_config("--enable-"+config) 1096: true 1097: elsif arg_config("--disable-"+config) 1098: false 1099: elsif block_given? 1100: yield(config, *defaults) 1101: else 1102: return *defaults 1103: end 1104: end
Returns Enumerable::Enumerator.new(self, method, *args).
e.g.:
str = "xyz"
enum = str.enum_for(:each_byte)
a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]
# protects an array from being modified
a = [1, 2, 3]
some_method(a.to_enum)
Source: show
static VALUE
obj_to_enum(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
{
VALUE meth = sym_each;
if (argc > 0) {
--argc;
meth = *argv++;
}
return rb_enumeratorize(obj, meth, argc, argv);
}
Parses environment variable env or its uppercase with splitting like a shell.
env defaults to the basename of the program.
Source: show
# File lib/optparse.rb, line 1482 1482: def environment(env = File.basename($0, '.*')) 1483: env = ENV[env] || ENV[env.upcase] or return 1484: require 'shellwords' 1485: parse(*Shellwords.shellwords(env)) 1486: end
Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning.
Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).
The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:
1 == 1.0 #=> true 1.eql? 1.0 #=> false
Source: show
static VALUE
rb_obj_equal(obj1, obj2)
VALUE obj1, obj2;
{
if (obj1 == obj2) return Qtrue;
return Qfalse;
}
Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning.
Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).
The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:
1 == 1.0 #=> true 1.eql? 1.0 #=> false
Source: show
static VALUE
rb_obj_equal(obj1, obj2)
VALUE obj1, obj2;
{
if (obj1 == obj2) return Qtrue;
return Qfalse;
}
Adds to obj the instance methods from each module given as a parameter.
module Mod
def hello
"Hello from Mod.\n"
end
end
class Klass
def hello
"Hello from Klass.\n"
end
end
k = Klass.new
k.hello #=> "Hello from Klass.\n"
k.extend(Mod) #=> #<Klass:0x401b3bc8>
k.hello #=> "Hello from Mod.\n"
Source: show
static VALUE
rb_obj_extend(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
{
int i;
if (argc == 0) {
rb_raise(rb_eArgError, "wrong number of arguments (0 for 1)");
}
for (i=0; i<argc; i++) Check_Type(argv[i], T_MODULE);
while (argc--) {
rb_funcall(argv[argc], rb_intern("extend_object"), 1, obj);
rb_funcall(argv[argc], rb_intern("extended"), 1, obj);
}
return obj;
}
Source: show
# File ext/extmk.rb, line 95 95: def extmake(target) 96: print "#{$message} #{target}\n" 97: $stdout.flush 98: if $force_static or $static_ext[target] 99: $static = target 100: else 101: $static = false 102: end 103: 104: unless $ignore 105: return true if $nodynamic and not $static 106: end 107: 108: FileUtils.mkpath target unless File.directory?(target) 109: begin 110: dir = Dir.pwd 111: FileUtils.mkpath target unless File.directory?(target) 112: Dir.chdir target 113: top_srcdir = $top_srcdir 114: topdir = $topdir 115: hdrdir = $hdrdir 116: prefix = "../" * (target.count("/")+1) 117: $top_srcdir = relative_from(top_srcdir, prefix) 118: $hdrdir = relative_from(hdrdir, prefix) 119: $topdir = prefix + $topdir 120: $target = target 121: $mdir = target 122: $srcdir = File.join($top_srcdir, "ext", $mdir) 123: $preload = nil 124: $objs = "" 125: $srcs = "" 126: $compiled[target] = false 127: makefile = "./Makefile" 128: ok = File.exist?(makefile) 129: unless $ignore 130: rbconfig0 = Config::CONFIG 131: mkconfig0 = CONFIG 132: rbconfig = { 133: "hdrdir" => $hdrdir, 134: "srcdir" => $srcdir, 135: "topdir" => $topdir, 136: } 137: mkconfig = { 138: "hdrdir" => "$(top_srcdir)", 139: "srcdir" => "$(top_srcdir)/ext/#{$mdir}", 140: "topdir" => $topdir, 141: } 142: rbconfig0.each_pair {|key, val| rbconfig[key] ||= val.dup} 143: mkconfig0.each_pair {|key, val| mkconfig[key] ||= val.dup} 144: Config.module_eval { 145: remove_const(:CONFIG) 146: const_set(:CONFIG, rbconfig) 147: remove_const(:MAKEFILE_CONFIG) 148: const_set(:MAKEFILE_CONFIG, mkconfig) 149: } 150: Object.class_eval { 151: remove_const(:CONFIG) 152: const_set(:CONFIG, mkconfig) 153: } 154: begin 155: $extconf_h = nil 156: ok &&= extract_makefile(makefile) 157: conf = ["#{$srcdir}/makefile.rb", "#{$srcdir}/extconf.rb"].find {|f| File.exist?(f)} 158: if (($extconf_h && !File.exist?($extconf_h)) || 159: !(t = modified?(makefile, MTIMES)) || 160: [conf, "#{$srcdir}/depend"].any? {|f| modified?(f, [t])}) 161: then 162: ok = false 163: init_mkmf 164: Logging::logfile 'mkmf.log' 165: rm_f makefile 166: if conf 167: load $0 = conf 168: else 169: create_makefile(target) 170: end 171: $defs << "-DRUBY_EXPORT" if $static 172: ok = File.exist?(makefile) 173: end 174: rescue SystemExit 175: # ignore 176: ensure 177: rm_f "conftest*" 178: config = $0 179: $0 = $PROGRAM_NAME 180: end 181: end 182: ok = yield(ok) if block_given? 183: unless ok 184: open(makefile, "w") do |f| 185: f.print dummy_makefile(CONFIG["srcdir"]) 186: end 187: return true 188: end 189: args = sysquote($mflags) 190: unless $destdir.to_s.empty? or $mflags.include?("DESTDIR") 191: args += [sysquote("DESTDIR=" + relative_from($destdir, "../"+prefix))] 192: end 193: if $static 194: args += ["static"] unless $clean 195: $extlist.push [$static, $target, File.basename($target), $preload] 196: end 197: unless system($make, *args) 198: $ignore or $continue or return false 199: end 200: $compiled[target] = true 201: if $clean 202: FileUtils.rm_f("mkmf.log") 203: if $clean != true 204: FileUtils.rm_f([makefile, $extconf_h || "extconf.h"]) 205: end 206: File.unlink(makefile) rescue nil 207: end 208: if $static 209: $extflags ||= "" 210: $extlibs ||= [] 211: $extpath ||= [] 212: unless $mswin 213: $extflags = ($extflags.split | $DLDFLAGS.split | $LDFLAGS.split).join(" ") 214: end 215: $extlibs = merge_libs($extlibs, $libs.split, $LOCAL_LIBS.split) 216: $extpath |= $LIBPATH 217: end 218: ensure 219: unless $ignore 220: Config.module_eval { 221: remove_const(:CONFIG) 222: const_set(:CONFIG, rbconfig0) 223: remove_const(:MAKEFILE_CONFIG) 224: const_set(:MAKEFILE_CONFIG, mkconfig0) 225: } 226: Object.class_eval { 227: remove_const(:CONFIG) 228: const_set(:CONFIG, mkconfig0) 229: } 230: end 231: $top_srcdir = top_srcdir 232: $topdir = topdir 233: $hdrdir = hdrdir 234: Dir.chdir dir 235: end 236: begin 237: Dir.rmdir target 238: target = File.dirname(target) 239: rescue SystemCallError 240: break 241: end while true 242: true 243: end
Source: show
# File ext/extmk.rb, line 54 54: def extract_makefile(makefile, keep = true) 55: m = File.read(makefile) 56: if !(target = m[/^TARGET[ \t]*=[ \t]*(\S*)/, 1]) 57: return keep 58: end 59: installrb = {} 60: m.scan(/^install-rb-default:[ \t]*(\S+)\n\1:[ \t]*(\S+)/) {installrb[$2] = $1} 61: oldrb = installrb.keys.sort 62: newrb = install_rb(nil, "").collect {|d, *f| f}.flatten.sort 63: if target_prefix = m[/^target_prefix[ \t]*=[ \t]*\/(.*)/, 1] 64: target = "#{target_prefix}/#{target}" 65: end 66: unless oldrb == newrb 67: if $extout 68: newrb.each {|f| installrb.delete(f)} 69: unless installrb.empty? 70: config = CONFIG.dup 71: install_dirs(target_prefix).each {|var, val| config[var] = val} 72: FileUtils.rm_f(installrb.values.collect {|f| Config.expand(f, config)}, :verbose => true) 73: end 74: end 75: return false 76: end 77: $target = target 78: $extconf_h = m[/^RUBY_EXTCONF_H[ \t]*=[ \t]*(\S+)/, 1] 79: $static ||= m[/^EXTSTATIC[ \t]*=[ \t]*(\S+)/, 1] || false 80: /^STATIC_LIB[ \t]*=[ \t]*\S+/ =~ m or $static = nil 81: $preload = Shellwords.shellwords(m[/^preload[ \t]*=[ \t]*(.*)/, 1] || "") 82: $DLDFLAGS += " " + (m[/^dldflags[ \t]*=[ \t]*(.*)/, 1] || "") 83: if s = m[/^LIBS[ \t]*=[ \t]*(.*)/, 1] 84: s.sub!(/^#{Regexp.quote($LIBRUBYARG)} */, "") 85: s.sub!(/ *#{Regexp.quote($LIBS)}$/, "") 86: $libs = s 87: end 88: $objs = (m[/^OBJS[ \t]*=[ \t](.*)/, 1] || "").split 89: $srcs = (m[/^SRCS[ \t]*=[ \t](.*)/, 1] || "").split 90: $LOCAL_LIBS = m[/^LOCAL_LIBS[ \t]*=[ \t]*(.*)/, 1] || "" 91: $LIBPATH = Shellwords.shellwords(m[/^libpath[ \t]*=[ \t]*(.*)/, 1] || "") - %w[$(libdir) $(topdir)] 92: true 93: end
Source: show
# File ext/dl/install.rb, line 13 13: def find(dir, match = /./) 14: Dir.chdir(dir) 15: files = [] 16: Dir.new(".").each{|file| 17: if( file != "." && file != ".." ) 18: case File.ftype(file) 19: when "file" 20: if( file =~ match ) 21: files.push(File.join(dir,file)) 22: end 23: when "directory" 24: files += find(file, match).collect{|f| File.join(dir,f)} 25: end 26: end 27: } 28: Dir.chdir("..") 29: return files 30: end
Searches for the executable bin on path. The default path is your PATH environment variable. If that isn’t defined, it will resort to searching /usr/local/bin, /usr/ucb, /usr/bin and /bin.
If found, it will return the full path, including the executable name, of where it was found.
Note that this method does not actually affect the generated Makefile.
Source: show
# File lib/mkmf.rb, line 1033 1033: def find_executablefind_executable(bin, path = nil) 1034: checking_for checking_message(bin, path) do 1035: find_executable0(bin, path) 1036: end 1037: end
Instructs mkmf to search for the given header in any of the paths provided, and returns whether or not it was found in those paths.
If the header is found then the path it was found on is added to the list of included directories that are sent to the compiler (via the -I switch).
Source: show
# File lib/mkmf.rb, line 768 768: def find_header(header, *paths) 769: message = checking_message(header, paths) 770: header = cpp_include(header) 771: checking_for message do 772: if try_cpp(header) 773: true 774: else 775: found = false 776: paths.each do |dir| 777: opt = "-I#{dir}".quote 778: if try_cpp(header, opt) 779: $INCFLAGS << " " << opt 780: found = true 781: break 782: end 783: end 784: found 785: end 786: end 787: end
Returns whether or not the entry point func can be found within the library lib in one of the paths specified, where paths is an array of strings. If func is nil , then the main() function is used as the entry point.
If lib is found, then the path it was found on is added to the list of library paths searched and linked against.
Source: show
# File lib/mkmf.rb, line 684 684: def find_library(lib, func, *paths, &b) 685: func = "main" if !func or func.empty? 686: lib = with_config(lib+'lib', lib) 687: paths = paths.collect {|path| path.split(File::PATH_SEPARATOR)}.flatten 688: checking_for "#{func}() in #{LIBARG%lib}" do 689: libpath = $LIBPATH 690: libs = append_library($libs, lib) 691: begin 692: until r = try_func(func, libs, &b) or paths.empty? 693: $LIBPATH = libpath | [paths.shift] 694: end 695: if r 696: $libs = libs 697: libpath = nil 698: end 699: ensure 700: $LIBPATH = libpath if libpath 701: end 702: r 703: end 704: end
Returns where the static type type is defined.
You may also pass additional flags to opt which are then passed along to the compiler.
See also have_type.
Source: show
# File lib/mkmf.rb, line 860 860: def find_type(type, opt, *headers, &b) 861: opt ||= "" 862: fmt = "not found" 863: def fmt.%(x) 864: x ? x.respond_to?(:join) ? x.join(",") : x : self 865: end 866: checking_for checking_message(type, nil, opt), fmt do 867: headers.find do |h| 868: try_type(type, h, opt, &b) 869: end 870: end 871: end
Prevents further modifications to obj. A TypeError will be raised if modification is attempted. There is no way to unfreeze a frozen object. See also Object#frozen?.
a = [ "a", "b", "c" ] a.freeze a << "z"
produces:
prog.rb:3:in `<<': can't modify frozen array (TypeError)
from prog.rb:3
Source: show
VALUE
rb_obj_freeze(obj)
VALUE obj;
{
if (!OBJ_FROZEN(obj)) {
if (rb_safe_level() >= 4 && !OBJ_TAINTED(obj)) {
rb_raise(rb_eSecurityError, "Insecure: can't freeze object");
}
OBJ_FREEZE(obj);
}
return obj;
}
Returns the freeze status of obj.
a = [ "a", "b", "c" ] a.freeze #=> ["a", "b", "c"] a.frozen? #=> true
Source: show
static VALUE
rb_obj_frozen_p(obj)
VALUE obj;
{
if (OBJ_FROZEN(obj)) return Qtrue;
return Qfalse;
}
Source: show
# File lib/profiler.rb, line 49 49: def get_name(klass, id) 50: name = klass.to_s || "" 51: if klass.kind_of? Class 52: name += "#" 53: else 54: name += "." 55: end 56: name + id.id2name 57: end
getopts is obsolete. Use GetoptLong.
Source: show
# File lib/getopts.rb, line 24 24: def getopts(single_options, *options) 25: boolopts = {} 26: valopts = {} 27: 28: # 29: # set defaults 30: # 31: single_options.scan(/.:?/) do |opt| 32: if opt.size == 1 33: boolopts[opt] = false 34: else 35: valopts[opt[0, 1]] = nil 36: end 37: end if single_options 38: 39: options.each do |arg| 40: opt, val = arg.split(':', 2) 41: 42: if val 43: valopts[opt] = val.empty? ? nil : val 44: else 45: boolopts[opt] = false 46: end 47: end 48: 49: # 50: # scan 51: # 52: c = 0 53: argv = ARGV 54: 55: while arg = argv.shift 56: case arg 57: when /\A--(.*)/ 58: if $1.empty? # xinit -- -bpp 24 59: break 60: end 61: 62: opt, val = $1.split('=', 2) 63: 64: if opt.size == 1 65: argv.unshift arg 66: return nil 67: elsif valopts.key? opt # imclean --src +trash 68: valopts[opt] = val || argv.shift or return nil 69: elsif boolopts.key? opt # ruby --verbose 70: boolopts[opt] = true 71: else 72: argv.unshift arg 73: return nil 74: end 75: 76: c += 1 77: when /\A-(.+)/ 78: opts = $1 79: 80: until opts.empty? 81: opt = opts.slice!(0, 1) 82: 83: if valopts.key? opt 84: val = opts 85: 86: if val.empty? # ruby -e 'p $:' 87: valopts[opt] = argv.shift or return nil 88: else # cc -ohello ... 89: valopts[opt] = val 90: end 91: 92: c += 1 93: break 94: elsif boolopts.key? opt 95: boolopts[opt] = true # ruby -h 96: c += 1 97: else 98: argv.unshift arg 99: return nil 100: end 101: end 102: else 103: argv.unshift arg 104: break 105: end 106: end 107: 108: # 109: # set 110: # 111: $OPT = {} 112: 113: boolopts.each do |opt, val| 114: $OPT[opt] = val 115: 116: sopt = opt.gsub(/[^A-Za-z0-9_]/, '_') 117: eval "$OPT_#{sopt} = val" 118: end 119: valopts.each do |opt, val| 120: $OPT[opt] = val 121: 122: sopt = opt.gsub(/[^A-Za-z0-9_]/, '_') 123: eval "$OPT_#{sopt} = val" 124: end 125: 126: c 127: end
Wrapper method for getopts.rb.
params = ARGV.getopts("ab:", "foo", "bar:")
# params[:a] = true # -a
# params[:b] = "1" # -b1
# params[:foo] = "1" # --foo
# params[:bar] = "x" # --bar x
Source: show
# File lib/optparse.rb, line 1373 1373: def getopts(*args) 1374: argv = Array === args.first ? args.shift : default_argv 1375: single_options, *long_options = *args 1376: 1377: result = {} 1378: 1379: single_options.scan(/(.)(:)?/) do |opt, val| 1380: if val 1381: result[opt] = nil 1382: define("-#{opt} VAL") 1383: else 1384: result[opt] = false 1385: define("-#{opt}") 1386: end 1387: end if single_options 1388: 1389: long_options.each do |arg| 1390: opt, val = arg.split(':', 2) 1391: if val 1392: result[opt] = val.empty? ? nil : val 1393: define("--#{opt} VAL") 1394: else 1395: result[opt] = false 1396: define("--#{opt}") 1397: end 1398: end 1399: 1400: parse_in_order(argv, result.method(:[]=)) 1401: result 1402: end
Generates a Fixnum hash value for this object. This function must have the property that a.eql?(b) implies a.hash == b.hash. The hash value is used by class Hash. Any hash value that exceeds the capacity of a Fixnum will be truncated before being used.
Source: show
VALUE
rb_obj_id(VALUE obj)
{
/*
* 32-bit VALUE space
* MSB ------------------------ LSB
* false 00000000000000000000000000000000
* true 00000000000000000000000000000010
* nil 00000000000000000000000000000100
* undef 00000000000000000000000000000110
* symbol ssssssssssssssssssssssss00001110
* object oooooooooooooooooooooooooooooo00 = 0 (mod sizeof(RVALUE))
* fixnum fffffffffffffffffffffffffffffff1
*
* object_id space
* LSB
* false 00000000000000000000000000000000
* true 00000000000000000000000000000010
* nil 00000000000000000000000000000100
* undef 00000000000000000000000000000110
* symbol 000SSSSSSSSSSSSSSSSSSSSSSSSSSS0 S...S % A = 4 (S...S = s...s * A + 4)
* object oooooooooooooooooooooooooooooo0 o...o % A = 0
* fixnum fffffffffffffffffffffffffffffff1 bignum if required
*
* where A = sizeof(RVALUE)/4
*
* sizeof(RVALUE) is
* 20 if 32-bit, double is 4-byte aligned
* 24 if 32-bit, double is 8-byte aligned
* 40 if 64-bit
*/
if (TYPE(obj) == T_SYMBOL) {
return (SYM2ID(obj) * sizeof(RVALUE) + (4 << 2)) | FIXNUM_FLAG;
}
if (SPECIAL_CONST_P(obj)) {
return LONG2NUM((long)obj);
}
return (VALUE)((long)obj|FIXNUM_FLAG);
}
Returns whether or not the constant const is defined. You may optionally pass the type of const as [const, type], like as:
have_const(%w[PTHREAD_MUTEX_INITIALIZER pthread_mutex_t], "pthread.h")
You may also pass additional headers to check against in addition to the common header files, and additional flags to opt which are then passed along to the compiler.
If found, a macro is passed as a preprocessor constant to the compiler using the type name, in uppercase, prepended with ‘HAVE_CONST_’.
For example, if have_const(‘foo’) returned true, then the HAVE_CONST_FOO preprocessor macro would be passed to the compiler.
Source: show
# File lib/mkmf.rb, line 906 906: def have_const(const, headers = nil, opt = "", &b) 907: checking_for checking_message([*const].compact.join(' '), headers, opt) do 908: try_const(const, headers, opt, &b) 909: end 910: end
Returns whether or not the function func can be found in the common header files, or within any headers that you provide. If found, a macro is passed as a preprocessor constant to the compiler using the function name, in uppercase, prepended with ‘HAVE_’.
For example, if have_func(‘foo’) returned true, then the HAVE_FOO preprocessor macro would be passed to the compiler.
Source: show
# File lib/mkmf.rb, line 714 714: def have_func(func, headers = nil, &b) 715: checking_for checking_message("#{func}()", headers) do 716: if try_func(func, $libs, headers, &b) 717: $defs.push(format("-DHAVE_%s", func.tr_cpp)) 718: true 719: else 720: false 721: end 722: end 723: end
Returns whether or not the given header file can be found on your system. If found, a macro is passed as a preprocessor constant to the compiler using the header file name, in uppercase, prepended with ‘HAVE_’.
For example, if have_header(‘foo.h’) returned true, then the HAVE_FOO_H preprocessor macro would be passed to the compiler.
Source: show
# File lib/mkmf.rb, line 751 751: def have_header(header, &b) 752: checking_for header do 753: if try_cpp(cpp_include(header), &b) 754: $defs.push(format("-DHAVE_%s", header.tr("a-z./\055", "A-Z___"))) 755: true 756: else 757: false 758: end 759: end 760: end
Returns whether or not the given entry point func can be found within lib. If func is nil, the ‘main()’ entry point is used by default. If found, it adds the library to list of libraries to be used when linking your extension.
If headers are provided, it will include those header files as the header files it looks in when searching for func.
The real name of the library to be linked can be altered by ’—with-FOOlib’ configuration option.
Source: show
# File lib/mkmf.rb, line 659 659: def have_library(lib, func = nil, headers = nil, &b) 660: func = "main" if !func or func.empty? 661: lib = with_config(lib+'lib', lib) 662: checking_for checking_message("#{func}()", LIBARG%lib) do 663: if COMMON_LIBS.include?(lib) 664: true 665: else 666: libs = append_library($libs, lib) 667: if try_func(func, libs, headers, &b) 668: $libs = libs 669: true 670: else 671: false 672: end 673: end 674: end 675: end
Returns whether or not macro is defined either in the common header files or within any headers you provide.
Any options you pass to opt are passed along to the compiler.
Source: show
# File lib/mkmf.rb, line 642 642: def have_macro(macro, headers = nil, opt = "", &b) 643: checking_for checking_message(macro, headers, opt) do 644: macro_defined?(macro, cpp_include(headers), opt, &b) 645: end 646: end
Source: show
# File ext/readline/extconf.rb, line 5 5: def have_readline_header(header) 6: if have_header(header) 7: $readline_headers.push(header) 8: return true 9: else 10: return false 11: end 12: end
Source: show
# File ext/readline/extconf.rb, line 14 14: def have_readline_var(var) 15: return have_var(var, $readline_headers) 16: end
Returns whether or not the struct of type type contains member. If it does not, or the struct type can’t be found, then false is returned. You may optionally specify additional headers in which to look for the struct (in addition to the common header files).
If found, a macro is passed as a preprocessor constant to the compiler using the member name, in uppercase, prepended with ‘HAVE_ST_’.
For example, if have_struct_member(‘struct foo’, ‘bar’) returned true, then the HAVE_ST_BAR preprocessor macro would be passed to the compiler.
Source: show
# File lib/mkmf.rb, line 800 800: def have_struct_member(type, member, headers = nil, &b) 801: checking_for checking_message("#{type}.#{member}", headers) do 802: if try_compile("\#{COMMON_HEADERS}\n\#{cpp_include(headers)}\n/*top*/\nint main() { return 0; }\nint s = (char *)&((\#{type}*)0)->\#{member} - (char *)0;\n", &b) 803: $defs.push(format("-DHAVE_ST_%s", member.tr_cpp)) 804: true 805: else 806: false 807: end 808: end 809: end
Returns whether or not the static type type is defined. You may optionally pass additional headers to check against in addition to the common header files.
You may also pass additional flags to opt which are then passed along to the compiler.
If found, a macro is passed as a preprocessor constant to the compiler using the type name, in uppercase, prepended with ‘HAVE_TYPE_’.
For example, if have_type(‘foo’) returned true, then the HAVE_TYPE_FOO preprocessor macro would be passed to the compiler.
Source: show
# File lib/mkmf.rb, line 847 847: def have_type(type, headers = nil, opt = "", &b) 848: checking_for checking_message(type, headers, opt) do 849: try_type(type, headers, opt, &b) 850: end 851: end
Returns whether or not the variable var can be found in the common header files, or within any headers that you provide. If found, a macro is passed as a preprocessor constant to the compiler using the variable name, in uppercase, prepended with ‘HAVE_’.
For example, if have_var(‘foo’) returned true, then the HAVE_FOO preprocessor macro would be passed to the compiler.
Source: show
# File lib/mkmf.rb, line 733 733: def have_var(var, headers = nil, &b) 734: checking_for checking_message(var, headers) do 735: if try_var(var, headers, &b) 736: $defs.push(format("-DHAVE_%s", var.tr_cpp)) 737: true 738: else 739: false 740: end 741: end 742: end
Display help message.
ruby -run -e help [COMMAND]
Source: show
# File lib/un.rb, line 222 222: def help 223: setup do |argv,| 224: all = argv.empty? 225: open(__FILE__) do |me| 226: while me.gets("##\n") 227: if help = me.gets("\n\n") 228: if all or argv.delete help[/-e \w+/].sub(/-e /, "") 229: print help.gsub(/^# ?/, "") 230: end 231: end 232: end 233: end 234: end 235: end
Returns option summary string.
Source: show
# File lib/optparse.rb, line 977 977: def help; summarize(banner.to_s.sub(/\n?\z/, "\n")) end
Soon-to-be deprecated version of Object#object_id.
Source: show
VALUE
rb_obj_id_obsolete(obj)
VALUE obj;
{
rb_warn("Object#id will be deprecated; use Object#object_id");
return rb_obj_id(obj);
}
Source: show
# File lib/optparse.rb, line 772 772: def inc(*args) 773: self.class.inc(*args) 774: end
Returns a string containing a human-readable representation of obj. If not overridden, uses the to_s method to generate the string.
[ 1, 2, 3..4, 'five' ].inspect #=> "[1, 2, 3..4, \"five\"]" Time.new.inspect #=> "Wed Apr 09 08:54:39 CDT 2003"
Source: show
static VALUE
rb_obj_inspect(obj)
VALUE obj;
{
if (TYPE(obj) == T_OBJECT
&& ROBJECT(obj)->iv_tbl
&& ROBJECT(obj)->iv_tbl->num_entries > 0) {
VALUE str;
size_t len;
const char *c = rb_obj_classname(obj);
if (rb_inspecting_p(obj)) {
len = strlen(c)+10+16+1;
str = rb_str_new(0, len); /* 10:tags 16:addr 1:nul */
snprintf(RSTRING(str)->ptr, len, "#<%s:0x%lx ...>", c, obj);
RSTRING(str)->len = strlen(RSTRING(str)->ptr);
return str;
}
len = strlen(c)+6+16+1;
str = rb_str_new(0, len); /* 6:tags 16:addr 1:nul */
snprintf(RSTRING(str)->ptr, len, "-<%s:0x%lx", c, obj);
RSTRING(str)->len = strlen(RSTRING(str)->ptr);
return rb_protect_inspect(inspect_obj, obj, str);
}
return rb_funcall(obj, rb_intern("to_s"), 0, 0);
}
Source: show
# File instruby.rb, line 131 131: def install(src, dest, options = {}) 132: options[:preserve] = true 133: super(src, with_destdir(dest), options) 134: if $installed_list 135: dest = File.join(dest, File.basename(src)) if $made_dirs[dest] 136: $installed_list.puts dest 137: end 138: end
Copy SOURCE to DEST.
ruby -run -e install -- [OPTION] SOURCE DEST
-p apply access/modification times of SOURCE files to
corresponding destination files
-m set permission mode (as in chmod), instead of 0755
-v verbose
Source: show
# File lib/un.rb, line 177 177: def install 178: setup("pm:") do |argv, options| 179: options[:mode] = (mode = options.delete :m) ? mode.oct : 0755 180: options[:preserve] = true if options.delete :p 181: dest = argv.pop 182: argv = argv[0] if argv.size == 1 183: FileUtils.install argv, dest, options 184: end 185: end
Source: show
# File ext/dl/install.rb, line 32 32: def install() 33: rb_files = find(File.join(".","lib"), /.rb$/) 34: 35: SO_LIBS.each{|f| 36: File.makedirs($rubylibdir, "#{$archdir}") 37: File.install(f, File.join($archdir,f), 0555, true) 38: } 39: 40: rb_files.each{|f| 41: origfile = f 42: instfile = File.join($rubylibdir, origfile.sub("./lib/","")) 43: instdir = File.dirname(instfile) 44: File.makedirs(instdir) 45: File.install(origfile, instfile, 0644, true) 46: } 47: end
Source: show
# File instruby.rb, line 124 124: def install?install?install?(*types, &block) 125: $install_procs[:all] <<= block 126: types.each do |type| 127: $install_procs[type] <<= block 128: end 129: end
Source: show
# File instruby.rb, line 159 159: def install_recursive(srcdir, dest, options = {}) 160: opts = options.clone 161: noinst = opts.delete(:no_install) 162: glob = opts.delete(:glob) || "*" 163: subpath = srcdir.size..-1 164: Dir.glob("#{srcdir}/**/#{glob}") do |src| 165: case base = File.basename(src) 166: when /\A\#.*\#\z/, /~\z/ 167: next 168: end 169: if noinst 170: if Array === noinst 171: next if noinst.any? {|n| File.fnmatch?(n, base)} 172: else 173: next if File.fnmatch?(noinst, base) 174: end 175: end 176: d = dest + src[subpath] 177: if File.directory?(src) 178: makedirs(d) 179: else 180: makedirs(File.dirname(d)) 181: install src, d, opts 182: end 183: end 184: end
Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj’s instance variables. In the version of instance_eval that takes a String, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors.
class Klass
def initialize
@secret = 99
end
end
k = Klass.new
k.instance_eval { @secret } #=> 99
Source: show
VALUE
rb_obj_instance_eval(argc, argv, self)
int argc;
VALUE *argv;
VALUE self;
{
VALUE klass;
if (SPECIAL_CONST_P(self)) {
klass = Qnil;
}
else {
klass = rb_singleton_class(self);
}
return specific_eval(argc, argv, klass, self);
}
Executes the given block within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj’s instance variables. Arguments are passed as block parameters.
class KlassWithSecret
def initialize
@secret = 99
end
end
k = KlassWithSecret.new
k.instance_exec(5) {|x| @secret+x } #=> 104
Source: show
VALUE
rb_obj_instance_exec(argc, argv, self)
int argc;
VALUE *argv;
VALUE self;
{
VALUE klass;
if (SPECIAL_CONST_P(self)) {
klass = Qnil;
}
else {
klass = rb_singleton_class(self);
}
return yield_under(klass, self, rb_ary_new4(argc, argv));
}
Returns true if obj is an instance of the given class. See also Object#kind_of?.
Source: show
VALUE
rb_obj_is_instance_of(obj, c)
VALUE obj, c;
{
switch (TYPE(c)) {
case T_MODULE:
case T_CLASS:
case T_ICLASS:
break;
default:
rb_raise(rb_eTypeError, "class or module required");
}
if (rb_obj_class(obj) == c) return Qtrue;
return Qfalse;
}
Returns true if the given instance variable is defined in obj.
class Fred
def initialize(p1, p2)
@a, @b = p1, p2
end
end
fred = Fred.new('cat', 99)
fred.instance_variable_defined?(:@a) #=> true
fred.instance_variable_defined?("@b") #=> true
fred.instance_variable_defined?("@c") #=> false
Source: show
static VALUE
rb_obj_ivar_defined(obj, iv)
VALUE obj, iv;
{
ID id = rb_to_id(iv);
if (!rb_is_instance_id(id)) {
rb_name_error(id, "`%s' is not allowed as an instance variable name", rb_id2name(id));
}
return rb_ivar_defined(obj, id);
}
Returns the value of the given instance variable, or nil if the instance variable is not set. The @ part of the variable name should be included for regular instance variables. Throws a NameError exception if the supplied symbol is not valid as an instance variable name.
class Fred
def initialize(p1, p2)
@a, @b = p1, p2
end
end
fred = Fred.new('cat', 99)
fred.instance_variable_get(:@a) #=> "cat"
fred.instance_variable_get("@b") #=> 99
Source: show
static VALUE
rb_obj_ivar_get(obj, iv)
VALUE obj, iv;
{
ID id = rb_to_id(iv);
if (!rb_is_instance_id(id)) {
rb_name_error(id, "`%s' is not allowed as an instance variable name", rb_id2name(id));
}
return rb_ivar_get(obj, id);
}
Source: show
# File lib/soap/soap.rb, line 123 123: def instance_variable_get(ivarname) 124: instance_eval(ivarname) 125: end
Sets the instance variable names by symbol to object, thereby frustrating the efforts of the class’s author to attempt to provide proper encapsulation. The variable did not have to exist prior to this call.
class Fred
def initialize(p1, p2)
@a, @b = p1, p2
end
end
fred = Fred.new('cat', 99)
fred.instance_variable_set(:@a, 'dog') #=> "dog"
fred.instance_variable_set(:@c, 'cat') #=> "cat"
fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
Source: show
static VALUE
rb_obj_ivar_set(obj, iv, val)
VALUE obj, iv, val;
{
ID id = rb_to_id(iv);
if (!rb_is_instance_id(id)) {
rb_name_error(id, "`%s' is not allowed as an instance variable name", rb_id2name(id));
}
return rb_ivar_set(obj, id, val);
}
Source: show
# File lib/soap/soap.rb, line 127 127: def instance_variable_set(ivarname, value) 128: instance_eval("#{ivarname} = value") 129: end
Returns an array of instance variable names for the receiver. Note that simply defining an accessor does not create the corresponding instance variable.
class Fred
attr_accessor :a1
def initialize
@iv = 3
end
end
Fred.new.instance_variables #=> ["@iv"]
Source: show
VALUE
rb_obj_instance_variables(obj)
VALUE obj;
{
VALUE ary;
ary = rb_ary_new();
switch (TYPE(obj)) {
case T_OBJECT:
case T_CLASS:
case T_MODULE:
if (ROBJECT(obj)->iv_tbl) {
st_foreach_safe(ROBJECT(obj)->iv_tbl, ivar_i, ary);
}
break;
default:
if (!generic_iv_tbl) break;
if (FL_TEST(obj, FL_EXIVAR) || rb_special_const_p(obj)) {
st_data_t tbl;
if (st_lookup(generic_iv_tbl, obj, &tbl)) {
st_foreach_safe((st_table *)tbl, ivar_i, ary);
}
}
break;
}
return ary;
}
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.
module M; end
class A
include M
end
class B < A; end
class C < B; end
b = B.new
b.instance_of? A #=> false
b.instance_of? B #=> true
b.instance_of? C #=> false
b.instance_of? M #=> false
b.kind_of? A #=> true
b.kind_of? B #=> true
b.kind_of? C #=> false
b.kind_of? M #=> true
Source: show
VALUE
rb_obj_is_kind_of(obj, c)
VALUE obj, c;
{
VALUE cl = CLASS_OF(obj);
switch (TYPE(c)) {
case T_MODULE:
case T_CLASS:
case T_ICLASS:
break;
default:
rb_raise(rb_eTypeError, "class or module required");
}
while (cl) {
if (cl == c || RCLASS(cl)->m_tbl == RCLASS(c)->m_tbl)
return Qtrue;
cl = RCLASS(cl)->super;
}
return Qfalse;
}
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.
module M; end
class A
include M
end
class B < A; end
class C < B; end
b = B.new
b.instance_of? A #=> false
b.instance_of? B #=> true
b.instance_of? C #=> false
b.instance_of? M #=> false
b.kind_of? A #=> true
b.kind_of? B #=> true
b.kind_of? C #=> false
b.kind_of? M #=> true
Source: show
VALUE
rb_obj_is_kind_of(obj, c)
VALUE obj, c;
{
VALUE cl = CLASS_OF(obj);
switch (TYPE(c)) {
case T_MODULE:
case T_CLASS:
case T_ICLASS:
break;
default:
rb_raise(rb_eTypeError, "class or module required");
}
while (cl) {
if (cl == c || RCLASS(cl)->m_tbl == RCLASS(c)->m_tbl)
return Qtrue;
cl = RCLASS(cl)->super;
}
return Qfalse;
}
Create a link to the specified TARGET with LINK_NAME.
ruby -run -e ln -- [OPTION] TARGET LINK_NAME -s make symbolic links instead of hard links -f remove existing destination files -v verbose
Source: show
# File lib/un.rb, line 89 89: def ln 90: setup("sf") do |argv, options| 91: cmd = "ln" 92: cmd += "_s" if options.delete :s 93: options[:force] = true if options.delete :f 94: dest = argv.pop 95: argv = argv[0] if argv.size == 1 96: FileUtils.send cmd, argv, dest, options 97: end 98: end
Source: show
# File instruby.rb, line 140 140: def ln_sf(src, dest) 141: super(src, with_destdir(dest)) 142: $installed_list.puts dest if $installed_list 143: end
Loads options from file names as filename. Does nothing when the file is not present. Returns whether successfully loaded.
filename defaults to basename of the program without suffix in a directory ~/.options.
Source: show
# File lib/optparse.rb, line 1462 1462: def load(filename = nil) 1463: begin 1464: filename ||= File.expand_path(File.basename($0, '.*'), '~/.options') 1465: rescue 1466: return false 1467: end 1468: begin 1469: parse(*IO.readlines(filename).each {|s| s.chomp!}) 1470: true 1471: rescue Errno::ENOENT, Errno::ENOTDIR 1472: false 1473: end 1474: end
Creates an OptionParser::Switch from the parameters. The parsed argument value is passed to the given block, where it can be processed.
See at the beginning of OptionParser for some full examples.
opts can include the following elements:
- Argument style:
- One of the following:
:NONE, :REQUIRED, :OPTIONAL
- Argument pattern:
- Acceptable option argument format, must be pre-defined with
OptionParser.accept or OptionParser#accept, or Regexp. This can appear once or assigned as String if not present, otherwise causes an ArgumentError. Examples:
Float, Time, Array
- Possible argument values:
- Hash or Array.
[:text, :binary, :auto] %w[iso-2022-jp shift_jis euc-jp utf8 binary] { "jis" => "iso-2022-jp", "sjis" => "shift_jis" } - Long style switch:
- Specifies a long style switch which takes a mandatory, optional or no
argument. It’s a string of the following form:
"--switch=MANDATORY" or "--switch MANDATORY" "--switch[=OPTIONAL]" "--switch"
- Short style switch:
- Specifies short style switch which takes a mandatory, optional or no
argument. It’s a string of the following form:
"-xMANDATORY" "-x[OPTIONAL]" "-x"
There is also a special form which matches character range (not full set of regular expression):
"-[a-z]MANDATORY" "-[a-z][OPTIONAL]" "-[a-z]"
- Argument style and description:
- Instead of specifying mandatory or optional arguments directly in the
switch parameter, this separate parameter can be used.
"=MANDATORY" "=[OPTIONAL]"
- Description:
- Description string for the option.
"Run verbosely"
- Handler:
- Handler for the parsed argument value. Either give a block or pass a Proc or Method as an argument.
Source: show
# File lib/optparse.rb, line 1064 1064: def make_switch(opts, block = nil) 1065: short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], [] 1066: ldesc, sdesc, desc, arg = [], [], [] 1067: default_style = Switch::NoArgument 1068: default_pattern = nil 1069: klass = nil 1070: o = nil 1071: n, q, a = nil 1072: 1073: opts.each do |o| 1074: # argument class 1075: next if search(:atype, o) do |pat, c| 1076: klass = notwice(o, klass, 'type') 1077: if not_style and not_style != Switch::NoArgument 1078: not_pattern, not_conv = pat, c 1079: else 1080: default_pattern, conv = pat, c 1081: end 1082: end 1083: 1084: # directly specified pattern(any object possible to match) 1085: if !(String === o) and o.respond_to?(:match) 1086: pattern = notwice(o, pattern, 'pattern') 1087: conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert) 1088: next 1089: end 1090: 1091: # anything others 1092: case o 1093: when Proc, Method 1094: block = notwice(o, block, 'block') 1095: when Array, Hash 1096: case pattern 1097: when CompletingHash 1098: when nil 1099: pattern = CompletingHash.new 1100: conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert) 1101: else 1102: raise ArgumentError, "argument pattern given twice" 1103: end 1104: o.each {|(o, *v)| pattern[o] = v.fetch(0) {o}} 1105: when Module 1106: raise ArgumentError, "unsupported argument type: #{o}" 1107: when *ArgumentStyle.keys 1108: style = notwice(ArgumentStyle[o], style, 'style') 1109: when /^--no-([^\[\]=\s]*)(.+)?/ 1110: q, a = $1, $2 1111: o = notwice(a ? Object : TrueClass, klass, 'type') 1112: not_pattern, not_conv = search(:atype, o) unless not_style 1113: not_style = (not_style || default_style).guess(arg = a) if a 1114: default_style = Switch::NoArgument 1115: default_pattern, conv = search(:atype, FalseClass) unless default_pattern 1116: ldesc << "--no-#{q}" 1117: long << 'no-' + (q = q.downcase) 1118: nolong << q 1119: when /^--\[no-\]([^\[\]=\s]*)(.+)?/ 1120: q, a = $1, $2 1121: o = notwice(a ? Object : TrueClass, klass, 'type') 1122: if a 1123: default_style = default_style.guess(arg = a) 1124: default_pattern, conv = search(:atype, o) unless default_pattern 1125: end 1126: ldesc << "--[no-]#{q}" 1127: long << (o = q.downcase) 1128: not_pattern, not_conv = search(:atype, FalseClass) unless not_style 1129: not_style = Switch::NoArgument 1130: nolong << 'no-' + o 1131: when /^--([^\[\]=\s]*)(.+)?/ 1132: q, a = $1, $2 1133: if a 1134: o = notwice(NilClass, klass, 'type') 1135: default_style = default_style.guess(arg = a) 1136: default_pattern, conv = search(:atype, o) unless default_pattern 1137: end 1138: ldesc << "--#{q}" 1139: long << (o = q.downcase) 1140: when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/ 1141: q, a = $1, $2 1142: o = notwice(Object, klass, 'type') 1143: if a 1144: default_style = default_style.guess(arg = a) 1145: default_pattern, conv = search(:atype, o) unless default_pattern 1146: end 1147: sdesc << "-#{q}" 1148: short << Regexp.new(q) 1149: when /^-(.)(.+)?/ 1150: q, a = $1, $2 1151: if a 1152: o = notwice(NilClass, klass, 'type') 1153: default_style = default_style.guess(arg = a) 1154: default_pattern, conv = search(:atype, o) unless default_pattern 1155: end 1156: sdesc << "-#{q}" 1157: short << q 1158: when /^=/ 1159: style = notwice(default_style.guess(arg = o), style, 'style') 1160: default_pattern, conv = search(:atype, Object) unless default_pattern 1161: else 1162: desc.push(o) 1163: end 1164: end 1165: 1166: default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern 1167: if !(short.empty? and long.empty?) 1168: s = (style || default_style).new(pattern || default_pattern, 1169: conv, sdesc, ldesc, arg, desc, block) 1170: elsif !block 1171: raise ArgumentError, "no switch given" if style or pattern 1172: s = desc 1173: else 1174: short << pattern 1175: s = (style || default_style).new(pattern, 1176: conv, nil, nil, arg, desc, block) 1177: end 1178: return s, short, long, 1179: (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style), 1180: nolong 1181: end
Source: show
# File instruby.rb, line 146 146: def makedirs(dirs) 147: dirs = fu_list(dirs) 148: dirs.collect! do |dir| 149: realdir = with_destdir(dir) 150: realdir unless $made_dirs.fetch(dir) do 151: $made_dirs[dir] = true 152: $installed_list.puts(File.join(dir, "")) if $installed_list 153: File.directory?(realdir) 154: end 155: end.compact! 156: super(dirs, :mode => $dir_mode) unless dirs.empty? 157: end
Looks up the named method as a receiver in obj, returning a Method object (or raising NameError). The Method object acts as a closure in obj’s object instance, so instance variables and the value of self remain available.
class Demo
def initialize(n)
@iv = n
end
def hello()
"Hello, @iv = #{@iv}"
end
end
k = Demo.new(99)
m = k.method(:hello)
m.call #=> "Hello, @iv = 99"
l = Demo.new('Fred')
m = l.method("hello")
m.call #=> "Hello, @iv = Fred"
Source: show
VALUE
rb_obj_method(obj, vid)
VALUE obj;
VALUE vid;
{
return mnew(CLASS_OF(obj), obj, rb_to_id(vid), rb_cMethod);
}
Returns a list of the names of methods publicly accessible in obj. This will include all the methods accessible in obj’s ancestors.
class Klass
def kMethod()
end
end
k = Klass.new
k.methods[0..9] #=> ["kMethod", "freeze", "nil?", "is_a?",
"class", "instance_variable_set",
"methods", "extend", "__send__", "instance_eval"]
k.methods.length #=> 42
Source: show
static VALUE
rb_obj_methods(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
{
retry:
if (argc == 0) {
VALUE args[1];
args[0] = Qtrue;
return rb_class_instance_methods(1, args, CLASS_OF(obj));
}
else {
VALUE recur;
rb_scan_args(argc, argv, "1", &recur);
if (RTEST(recur)) {
argc = 0;
goto retry;
}
return rb_obj_singleton_methods(argc, argv, obj);
}
}
Create the DIR, if they do not already exist.
ruby -run -e mkdir -- [OPTION] DIR -p no error if existing, make parent directories as needed -v verbose
Source: show
# File lib/un.rb, line 144 144: def mkdir 145: setup("p") do |argv, options| 146: cmd = "mkdir" 147: cmd += "_p" if options.delete :p 148: FileUtils.send cmd, argv, options 149: end 150: end
Source: show
# File ext/dl/mkcallback.rb, line 8 8: def mkfunc(rettype, fnum, argc) 9: args = (0..(argc-1)).collect{|i| "long arg#{i}"}.join(", ") 10: 11: subst_code = (0..(argc-1)).collect{|i| 12: " buff[#{i.to_s}] = arg#{i.to_s};" 13: }.join("\n") 14: 15: ret_code = 16: if( DLTYPE[rettype][:c2rb] ) 17: " return #{DLTYPE[rettype][:rb2c]['retval']};" 18: else 19: " /* no return value */" 20: end 21: 22: code = [ 23: "static #{DLTYPE[rettype][:ctype]}", 24: "rb_dl_callback_func_#{rettype.to_s}_#{fnum.to_s}(#{args})", 25: "{", 26: " VALUE retval, proto, proc, obj;", 27: " VALUE argv[#{argc.to_s}];", 28: " int argc;", 29: " long buff[#{argc.to_s}];", 30: "", 31: subst_code, 32: "", 33: " obj = rb_hash_aref(DLFuncTable, rb_assoc_new(INT2NUM(#{rettype.to_s}),INT2NUM(#{fnum.to_s})));", 34: " if(NIL_P(obj))", 35: " rb_raise(rb_eDLError, \"callback function does not exist in DL::FuncTable\");", 36: " Check_Type(obj, T_ARRAY);", 37: " proto = rb_ary_entry(obj, 0);", 38: " proc = rb_ary_entry(obj, 1);", 39: " Check_Type(proto, T_STRING);", 40: " if( RSTRING(proto)->len >= #{argc.to_s} )", 41: " rb_raise(rb_eArgError, \"too many arguments\");", 42: " rb_dl_scan_callback_args(buff, RSTRING(proto)->ptr, &argc, argv);", 43: " retval = rb_funcall2(proc, id_call, argc, argv);", 44: "", 45: ret_code, 46: "}", 47: ].join("\n") 48: 49: return code 50: end
Source: show
# File ext/dl/mkcbtable.rb, line 8 8: def mktable(rettype, fnum, argc) 9: code = 10: "rb_dl_callback_table[#{rettype}][#{fnum}] = &rb_dl_callback_func_#{rettype.to_s}_#{fnum};" 11: return code 12: end
Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.
ruby -run -e mv -- [OPTION] SOURCE DEST -v verbose
Source: show
# File lib/un.rb, line 108 108: def mv 109: setup do |argv, options| 110: dest = argv.pop 111: argv = argv[0] if argv.size == 1 112: FileUtils.mv argv, dest, options 113: end 114: end
Pushes a new List.
Source: show
# File lib/optparse.rb, line 943 943: def new 944: @stack.push(List.new) 945: if block_given? 946: yield self 947: else 948: self 949: end 950: end
call_seq:
nil.nil? => true <anything_else>.nil? => false
Only the object nil responds true to nil?.
Source: show
static VALUE
rb_false(obj)
VALUE obj;
{
return Qfalse;
}
Checks if an argument is given twice, in which case an ArgumentError is raised. Called from OptionParser#switch only.
| obj: | New argument. |
| prv: | Previously specified argument. |
| msg: | Exception message. |
Source: show
# File lib/optparse.rb, line 993 993: def notwice(obj, prv, msg) 994: unless !prv or prv == obj 995: begin 996: raise ArgumentError, "argument #{msg} given twice: #{obj}" 997: rescue 998: $@[0, 2] = nil 999: raise 1000: end 1001: end 1002: obj 1003: end
Source: show
# File ext/dl/type.rb, line 97 97: def num2types(num) 98: ts = [] 99: i = 0 100: t = tget(num,i) 101: while( (t != VOID && i > 0) || (i == 0) ) 102: ts.push(DLTYPE[t][:ctype]) 103: i += 1 104: t = tget(num,i) 105: end 106: ts 107: end
Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id. Object#object_id is a different concept from the :name notation, which returns the symbol id of name. Replaces the deprecated Object#id.
Source: show
VALUE
rb_obj_id(VALUE obj)
{
/*
* 32-bit VALUE space
* MSB ------------------------ LSB
* false 00000000000000000000000000000000
* true 00000000000000000000000000000010
* nil 00000000000000000000000000000100
* undef 00000000000000000000000000000110
* symbol ssssssssssssssssssssssss00001110
* object oooooooooooooooooooooooooooooo00 = 0 (mod sizeof(RVALUE))
* fixnum fffffffffffffffffffffffffffffff1
*
* object_id space
* LSB
* false 00000000000000000000000000000000
* true 00000000000000000000000000000010
* nil 00000000000000000000000000000100
* undef 00000000000000000000000000000110
* symbol 000SSSSSSSSSSSSSSSSSSSSSSSSSSS0 S...S % A = 4 (S...S = s...s * A + 4)
* object oooooooooooooooooooooooooooooo0 o...o % A = 0
* fixnum fffffffffffffffffffffffffffffff1 bignum if required
*
* where A = sizeof(RVALUE)/4
*
* sizeof(RVALUE) is
* 20 if 32-bit, double is 4-byte aligned
* 24 if 32-bit, double is 8-byte aligned
* 40 if 64-bit
*/
if (TYPE(obj) == T_SYMBOL) {
return (SYM2ID(obj) * sizeof(RVALUE) + (4 << 2)) | FIXNUM_FLAG;
}
if (SPECIAL_CONST_P(obj)) {
return LONG2NUM((long)obj);
}
return (VALUE)((long)obj|FIXNUM_FLAG);
}
Add option switch and handler. See make_switch for an explanation of parameters.
Source: show
# File lib/optparse.rb, line 1192 1192: def on(*opts, &block) 1193: define(*opts, &block) 1194: self 1195: end
Add option switch like with on, but at head of summary.
Source: show
# File lib/optparse.rb, line 1206 1206: def on_head(*opts, &block) 1207: define_head(*opts, &block) 1208: self 1209: end
Add option switch like with on, but at tail of summary.
Source: show
# File lib/optparse.rb, line 1220 1220: def on_tail(*opts, &block) 1221: define_tail(*opts, &block) 1222: self 1223: end
Source: show
# File ext/curses/rain.rb, line 7 7: def onsig(sig) 8: close_screen 9: exit sig 10: end
Source: show
# File instruby.rb, line 186 186: def open_for_install(path, mode) 187: data = open(realpath = with_destdir(path), "rb") {|f| f.read} rescue nil 188: newdata = yield 189: unless $dryrun 190: unless newdata == data 191: open(realpath, "wb", mode) {|f| f.write newdata} 192: end 193: File.chmod(mode, realpath) 194: end 195: $installed_list.puts path if $installed_list 196: end
Parses command line arguments argv in order. When a block is given, each non-option argument is yielded.
Returns the rest of argv left unparsed.
Source: show
# File lib/optparse.rb, line 1239 1239: def order(*argv, &block) 1240: argv = argv[0].dup if argv.size == 1 and Array === argv[0] 1241: order!(argv, &block) 1242: end
Same as order, but removes switches destructively.
Source: show
# File lib/optparse.rb, line 1247 1247: def order!(argv = default_argv, &nonopt) 1248: parse_in_order(argv, &nonopt) 1249: end
Source: show
# File ext/dl/mkcall.rb, line 8 8: def output_arg(x,i) 9: "args[#{i}].#{DLTYPE[x][:stmem]}" 10: end
Source: show
# File ext/dl/mkcall.rb, line 12 12: def output_args(types) 13: t = [] 14: types[1..-1].each_with_index{|x,i| t.push(output_arg(x,i))} 15: t.join(",") 16: end
Source: show
# File ext/dl/mkcall.rb, line 18 18: def output_callfunc(types) 19: t = types[0] 20: stmem = DLTYPE[t][:stmem] 21: ctypes = types2ctypes(types) 22: if( t == VOID ) 23: callstm = "(*f)(#{output_args(types)})" 24: else 25: callstm = "ret.#{stmem} = (*f)(#{output_args(types)})" 26: end 27: [ "{", 28: "#{ctypes[0]} (*f)(#{ctypes[1..-1].join(',')}) = func;", 29: "#{callstm};", 30: "}"].join(" ") 31: end
Source: show
# File ext/dl/mkcall.rb, line 33 33: def output_case(types) 34: num = types2num(types) 35: callfunc_stm = output_callfunc(types) 36: " case \#{num}:\n#ifdef DEBUG\n printf(\"\#{callfunc_stm}\\\\n\");\n#endif\n \#{callfunc_stm};\n break;\n" 37: end
Parses command line arguments argv in order when environment variable POSIXLY_CORRECT is set, and in permutation mode otherwise.
Source: show
# File lib/optparse.rb, line 1348 1348: def parse(*argv) 1349: argv = argv[0].dup if argv.size == 1 and Array === argv[0] 1350: parse!(argv) 1351: end
Same as parse, but removes switches destructively.
Source: show
# File lib/optparse.rb, line 1356 1356: def parse!(argv = default_argv) 1357: if ENV.include?('POSIXLY_CORRECT') 1358: order!(argv) 1359: else 1360: permute!(argv) 1361: end 1362: end
parseArgs is obsolete. Use OptionParser instead.
Source: show
# File lib/parsearg.rb, line 62 62: def parseArgs(argc, nopt, single_opts, *opts) 63: if (noOptions = getopts(single_opts, *opts)) == nil 64: printUsageAndExit() 65: end 66: if nopt 67: ex = nil 68: pos = 0 69: for o in nopt.split(/[()|&]/) 70: pos += o.length 71: ex = setExpression(ex, o, nopt[pos]) 72: pos += 1 73: end 74: begin 75: if !eval(ex) 76: printUsageAndExit() 77: end 78: rescue 79: print "Format Error!! : \"" + nopt + "\"\t[parseArgs]\n" 80: exit!(-1) 81: end 82: end 83: if ARGV.length < argc 84: printUsageAndExit() 85: end 86: return noOptions 87: end
Source: show
# File instruby.rb, line 17 17: def parse_args(argv = ARGV) 18: $mantype = 'doc' 19: $destdir = nil 20: $extout = nil 21: $make = 'make' 22: $mflags = [] 23: $install = [] 24: $installed_list = nil 25: $dryrun = false 26: $rdocdir = nil 27: $data_mode = 0644 28: $prog_mode = 0755 29: $dir_mode = nil 30: $script_mode = nil 31: $cmdtype = ('bat' if File::ALT_SEPARATOR == '\\') 32: mflags = [] 33: opt = OptionParser.new 34: opt.on('-n') {$dryrun = true} 35: opt.on('--dest-dir=DIR') {|dir| $destdir = dir} 36: opt.on('--extout=DIR') {|dir| $extout = (dir unless dir.empty?)} 37: opt.on('--make=COMMAND') {|make| $make = make} 38: opt.on('--mantype=MAN') {|man| $mantype = man} 39: opt.on('--make-flags=FLAGS', '--mflags', Shellwords) do |v| 40: if arg = v.first 41: arg.insert(0, '-') if /\A[^-][^=]*\Z/ =~ arg 42: end 43: $mflags.concat(v) 44: end 45: opt.on('-i', '--install=TYPE', 46: [:local, :bin, :"bin-arch", :"bin-comm", :lib, :man, :ext, :"ext-arch", :"ext-comm", :rdoc]) do |ins| 47: $install << ins 48: end 49: opt.on('--data-mode=OCTAL-MODE', OptionParser::OctalInteger) do |mode| 50: $data_mode = mode 51: end 52: opt.on('--prog-mode=OCTAL-MODE', OptionParser::OctalInteger) do |mode| 53: $prog_mode = mode 54: end 55: opt.on('--dir-mode=OCTAL-MODE', OptionParser::OctalInteger) do |mode| 56: $dir_mode = mode 57: end 58: opt.on('--script-mode=OCTAL-MODE', OptionParser::OctalInteger) do |mode| 59: $script_mode = mode 60: end 61: opt.on('--installed-list [FILENAME]') {|name| $installed_list = name} 62: opt.on('--rdoc-output [DIR]') {|dir| $rdocdir = dir} 63: opt.on('--cmd-type=TYPE', %w[bat cmd plain]) {|cmd| $cmdtype = (cmd unless cmd == 'plain')} 64: 65: opt.order!(argv) do |v| 66: case v 67: when /\AINSTALL[-_]([-\w]+)=(.*)/ 68: argv.unshift("--#{$1.tr('_', '-')}=#{$2}") 69: when /\A\w[-\w+]*=\z/ 70: mflags << v 71: when /\A\w[-\w+]*\z/ 72: $install << v.intern 73: else 74: raise OptionParser::InvalidArgument, v 75: end 76: end rescue abort [$!.message, opt].join("\n") 77: 78: $make, *rest = Shellwords.shellwords($make) 79: $mflags.unshift(*rest) unless rest.empty? 80: $mflags.unshift(*mflags) 81: 82: def $mflags.set?(flag) 83: grep(/\A-(?!-).*#{flag.chr}/i) { return true } 84: false 85: end 86: def $mflags.defined?(var) 87: grep(/\A#{var}=(.*)/) {return block_given? ? yield($1) : $1} 88: false 89: end 90: 91: if $mflags.set?(?n) 92: $dryrun = true 93: else 94: $mflags << '-n' if $dryrun 95: end 96: 97: $destdir ||= $mflags.defined?("DESTDIR") 98: if $extout ||= $mflags.defined?("EXTOUT") 99: Config.expand($extout) 100: end 101: 102: $continue = $mflags.set?(?k) 103: 104: if $installed_list ||= $mflags.defined?('INSTALLED_LIST') 105: Config.expand($installed_list, Config::CONFIG) 106: $installed_list = open($installed_list, "ab") 107: $installed_list.sync = true 108: end 109: 110: $rdocdir ||= $mflags.defined?('RDOCOUT') 111: 112: $dir_mode ||= $prog_mode | 0700 113: $script_mode ||= $prog_mode 114: end
Source: show
# File ext/extmk.rb, line 249 249: def parse_args() 250: $mflags = [] 251: 252: opts = nil 253: $optparser ||= OptionParser.new do |opts| 254: opts.on('-n') {$dryrun = true} 255: opts.on('--[no-]extension [EXTS]', Array) do |v| 256: $extension = (v == false ? [] : v) 257: end 258: opts.on('--[no-]extstatic [STATIC]', Array) do |v| 259: if ($extstatic = v) == false 260: $extstatic = [] 261: elsif v 262: $force_static = true if $extstatic.delete("static") 263: $extstatic = nil if $extstatic.empty? 264: end 265: end 266: opts.on('--dest-dir=DIR') do |v| 267: $destdir = v 268: end 269: opts.on('--extout=DIR') do |v| 270: $extout = (v unless v.empty?) 271: end 272: opts.on('--make=MAKE') do |v| 273: $make = v || 'make' 274: end 275: opts.on('--make-flags=FLAGS', '--mflags', Shellwords) do |v| 276: v.grep(/\A([-\w]+)=(.*)/) {$configure_args["--#{$1}"] = $2} 277: if arg = v.first 278: arg.insert(0, '-') if /\A[^-][^=]*\Z/ =~ arg 279: end 280: $mflags.concat(v) 281: end 282: opts.on('--message [MESSAGE]', String) do |v| 283: $message = v 284: end 285: end 286: begin 287: $optparser.parse!(ARGV) 288: rescue OptionParser::InvalidOption => e 289: retry if /^--/ =~ e.args[0] 290: $optparser.warn(e) 291: abort opts.to_s 292: end 293: 294: $destdir ||= '' 295: 296: $make, *rest = Shellwords.shellwords($make) 297: $mflags.unshift(*rest) unless rest.empty? 298: 299: def $mflags.set?(flag) 300: grep(/\A-(?!-).*#{flag.chr}/i) { return true } 301: false 302: end 303: def $mflags.defined?(var) 304: grep(/\A#{var}=(.*)/) {return $1} 305: false 306: end 307: 308: if $mflags.set?(?n) 309: $dryrun = true 310: else 311: $mflags.unshift '-n' if $dryrun 312: end 313: 314: $continue = $mflags.set?(?k) 315: if $extout 316: $extout = '$(topdir)/'+$extout 317: Config::CONFIG["extout"] = CONFIG["extout"] = $extout 318: $extout_prefix = $extout ? "$(extout)$(target_prefix)/" : "" 319: $mflags << "extout=#$extout" << "extout_prefix=#$extout_prefix" 320: end 321: end
Parses command line arguments argv in permutation mode and returns list of non-option arguments.
Source: show
# File lib/optparse.rb, line 1328 1328: def permute(*argv) 1329: argv = argv[0].dup if argv.size == 1 and Array === argv[0] 1330: permute!(argv) 1331: end
Same as permute, but removes switches destructively.
Source: show
# File lib/optparse.rb, line 1336 1336: def permute!(argv = default_argv) 1337: nonopts = [] 1338: arg = nil 1339: order!(argv) {|arg| nonopts << arg} 1340: argv[0, 0] = nonopts 1341: argv 1342: end
Source: show
# File lib/pp.rb, line 467 467: def pretty_print(q) 468: q.text inspect 469: end
Source: show
# File lib/pp.rb, line 459 459: def pretty_print_cycle(q) 460: q.text inspect 461: end
Source: show
# File lib/parsearg.rb, line 19 19: def printUsageAndExit() 20: if $USAGE 21: eval($USAGE) 22: end 23: exit() 24: end
Source: show
# File lib/profiler.rb, line 32 32: def print_profile(f) 33: stop_profile 34: total = Process.times[0] - @@start 35: if total == 0 then total = 0.01 end 36: data = @@map.values 37: data.sort!{|a,b| b[2] <=> a[2]} 38: sum = 0 39: f.printf " %% cumulative self self total\n" 40: f.printf " time seconds seconds calls ms/call ms/call name\n" 41: for d in data 42: sum += d[2] 43: f.printf "%6.2f %8.2f %8.2f %8d ", d[2]/total*100, sum, d[2], d[0] 44: f.printf "%8.2f %8.2f %s\n", d[2]*1000/d[0], d[1]*1000/d[0], get_name(*d[3]) 45: end 46: f.printf "%6.2f %8.2f %8.2f %8d ", 0.0, total, 0.0, 1 # ??? 47: f.printf "%8.2f %8.2f %s\n", 0.0, total*1000, "#toplevel" # ??? 48: end
Returns the list of private methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.
Source: show
static VALUE
rb_obj_private_methods(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
{
if (argc == 0) { /* hack to stop warning */
VALUE args[1];
args[0] = Qtrue;
return rb_class_private_instance_methods(1, args, CLASS_OF(obj));
}
return rb_class_private_instance_methods(argc, argv, CLASS_OF(obj));
}
Program name to be emitted in error message and default banner, defaults to $0.
Source: show
# File lib/optparse.rb, line 878 878: def program_name 879: @program_name || File.basename($0, '.*') 880: end
Returns the list of protected methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.
Source: show
static VALUE
rb_obj_protected_methods(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
{
if (argc == 0) { /* hack to stop warning */
VALUE args[1];
args[0] = Qtrue;
return rb_class_protected_instance_methods(1, args, CLASS_OF(obj));
}
return rb_class_protected_instance_methods(argc, argv, CLASS_OF(obj));
}
Returns the list of public methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.
Source: show
static VALUE
rb_obj_public_methods(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
{
if (argc == 0) { /* hack to stop warning */
VALUE args[1];
args[0] = Qtrue;
return rb_class_public_instance_methods(1, args, CLASS_OF(obj));
}
return rb_class_public_instance_methods(argc, argv, CLASS_OF(obj));
}
Source: show
# File ext/curses/rain.rb, line 12 12: def ranf 13: rand(32767).to_f / 32767 14: end
Source: show
# File ext/bigdecimal/sample/linear.rb, line 23 23: def rd_order(na) 24: printf("Number of equations ?") if(na <= 0) 25: n = ARGF.gets().to_i 26: end
Source: show
# File ext/dl/mkcall.rb, line 47 47: def rec_output(types = [VOID]) 48: print output_case(types) 49: if( types.length <= MAX_ARG ) 50: DLTYPE.keys.sort.each{|t| 51: if( t != VOID && DLTYPE[t][:sym] ) 52: rec_output(types + [t]) 53: end 54: } 55: end 56: end
Directs to reject specified class argument.
| t: | Argument class specifier, any object including Class. |
reject(t)
Source: show
# File lib/optparse.rb, line 837 837: def reject(*args, &blk) top.reject(*args, &blk) end
Source: show
# File ext/extmk.rb, line 45 45: def relative_from(path, base) 46: dir = File.join(path, "") 47: if File.expand_path(dir) == File.expand_path(dir, base) 48: path 49: else 50: File.join(base, path) 51: end 52: end
Release code
Source: show
# File lib/optparse.rb, line 903 903: def release 904: @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE) 905: end
Removes the last List.
Source: show
# File lib/optparse.rb, line 955 955: def remove 956: @stack.pop 957: end
Returns true> if obj responds to the given method. Private methods are included in the search only if the optional second parameter evaluates to true.
Source: show
static VALUE
obj_respond_to(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
{
VALUE mid, priv;
ID id;
rb_scan_args(argc, argv, "11", &mid, &priv);
id = rb_to_id(mid);
if (rb_method_boundp(CLASS_OF(obj), id, !RTEST(priv))) {
return Qtrue;
}
return Qfalse;
}
Remove the FILE
ruby -run -e rm -- [OPTION] FILE -f ignore nonexistent files -r remove the contents of directories recursively -v verbose
Source: show
# File lib/un.rb, line 126 126: def rm 127: setup("fr") do |argv, options| 128: cmd = "rm" 129: cmd += "_r" if options.delete :r 130: options[:force] = true if options.delete :f 131: FileUtils.send cmd, argv, options 132: end 133: end
Remove the DIR.
ruby -run -e rmdir -- [OPTION] DIR -v verbose
Source: show
# File lib/un.rb, line 160 160: def rmdir 161: setup do |argv, options| 162: FileUtils.rmdir argv, options 163: end 164: end
Source: show
# File ext/curses/view2.rb, line 57 57: def scroll_down 58: if( $top + $screen.maxy < $data_lines.length ) 59: $screen.scrl(1) 60: $top += 1 61: str = $data_lines[$top + $screen.maxy - 1] 62: if( str ) 63: $screen.setpos($screen.maxy - 1, 0) 64: $screen.addstr(str) 65: end 66: return true 67: else 68: return false 69: end 70: end
Source: show
# File ext/curses/view2.rb, line 42 42: def scroll_up 43: if( $top > 0 ) 44: $screen.scrl(-1) 45: $top -= 1 46: str = $data_lines[$top] 47: if( str ) 48: $screen.setpos(0, 0) 49: $screen.addstr(str) 50: end 51: return true 52: else 53: return false 54: end 55: end
Searches key in @stack for id hash and returns or yields the result.
Source: show
# File lib/optparse.rb, line 1427 1427: def search(id, key) 1428: block_given = block_given? 1429: visit(:search, id, key) do |k| 1430: return block_given ? yield(k) : k 1431: end 1432: end
Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.
class Klass
def hello(*args)
"Hello " + args.join(' ')
end
end
k = Klass.new
k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
Source: show
static VALUE
rb_f_send(argc, argv, recv)
int argc;
VALUE *argv;
VALUE recv;
{
VALUE vid;
if (argc == 0) rb_raise(rb_eArgError, "no method name given");
vid = *argv++; argc--;
PUSH_ITER(rb_block_given_p()?ITER_PRE:ITER_NOT);
vid = rb_call(CLASS_OF(recv), recv, rb_to_id(vid), argc, argv, 1, Qundef);
POP_ITER();
return vid;
}
Add separator in summary.
Source: show
# File lib/optparse.rb, line 1229 1229: def separator(string) 1230: top.append(string, nil, nil) 1231: end
Source: show
# File lib/parsearg.rb, line 44 44: def setExpression(ex, opt, op) 45: if !op 46: ex = sprintf("%s$OPT_%s", ex, opt) 47: return ex 48: end 49: case op.chr 50: when "(", ")" 51: ex = setParenthesis(ex, opt, op.chr) 52: when "|", "&" 53: ex = setOrAnd(ex, opt, op.chr) 54: else 55: return nil 56: end 57: return ex 58: end
Source: show
# File lib/parsearg.rb, line 35 35: def setOrAnd(ex, opt, c) 36: if opt != "" 37: ex = sprintf("%s$OPT_%s %s%s ", ex, opt, c, c) 38: else 39: ex = sprintf("%s %s%s ", ex, c, c) 40: end 41: return ex 42: end
Source: show
# File lib/parsearg.rb, line 26 26: def setParenthesis(ex, opt, c) 27: if opt != "" 28: ex = sprintf("%s$OPT_%s%s", ex, opt, c) 29: else 30: ex = sprintf("%s%s", ex, c) 31: end 32: return ex 33: end
Source: show
# File lib/un.rb, line 32 32: def setup(options = "") 33: ARGV.map! do |x| 34: case x 35: when /^-/ 36: x.delete "^-#{options}v" 37: when /[*?\[{]/ 38: Dir[x] 39: else 40: x 41: end 42: end 43: ARGV.flatten! 44: ARGV.delete_if{|x| x == "-"} 45: opt_hash = {} 46: OptionParser.new do |o| 47: options.scan(/.:?/) do |s| 48: o.on("-" + s.tr(":", " ")) do |val| 49: opt_hash[s.delete(":").intern] = val 50: end 51: end 52: o.on("-v") do opt_hash[:verbose] = true end 53: o.parse! 54: end 55: yield ARGV, opt_hash 56: end
Source: show
# File ext/curses/hello.rb, line 6 6: def show_message(message) 7: width = message.length + 6 8: win = Window.new(5, width, 9: (lines - 5) / 2, (cols - width) / 2) 10: win.box(?|, ?-) 11: win.setpos(2, 3) 12: win.addstr(message) 13: win.refresh 14: win.getch 15: win.close 16: end
Source: show
# File ext/curses/mouse.rb, line 6 6: def show_message(*msgs) 7: message = msgs.join 8: width = message.length + 6 9: win = Window.new(5, width, 10: (lines - 5) / 2, (cols - width) / 2) 11: win.keypad = true 12: win.attron(color_pair(COLOR_RED)){ 13: win.box(?|, ?-, ?+) 14: } 15: win.setpos(2, 3) 16: win.addstr(message) 17: win.refresh 18: win.getch 19: win.close 20: end
Returns an array of the names of singleton methods for obj. If the optional all parameter is true, the list will include methods in modules included in obj.
module Other
def three() end
end
class Single
def Single.four() end
end
a = Single.new
def a.one()
end
class << a
include Other
def two()
end
end
Single.singleton_methods #=> ["four"]
a.singleton_methods(false) #=> ["two", "one"]
a.singleton_methods #=> ["two", "one", "three"]
Source: show
VALUE
rb_obj_singleton_methods(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
{
VALUE recur, ary, klass;
st_table *list;
rb_scan_args(argc, argv, "01", &recur);
if (argc == 0) {
recur = Qtrue;
}
klass = CLASS_OF(obj);
list = st_init_numtable();
if (klass && FL_TEST(klass, FL_SINGLETON)) {
st_foreach(RCLASS(klass)->m_tbl, method_entry, (st_data_t)list);
klass = RCLASS(klass)->super;
}
if (RTEST(recur)) {
while (klass && (FL_TEST(klass, FL_SINGLETON) || TYPE(klass) == T_ICLASS)) {
st_foreach(RCLASS(klass)->m_tbl, method_entry, (st_data_t)list);
klass = RCLASS(klass)->super;
}
}
ary = rb_ary_new();
st_foreach(list, ins_methods_i, ary);
st_free_table(list);
return ary;
}
Source: show
# File lib/profiler.rb, line 23 23: def start_profile 24: @@start = Process.times[0] 25: @@stack = [] 26: @@map = {} 27: set_trace_func PROFILE_PROC 28: end
Source: show
# File lib/profiler.rb, line 29 29: def stop_profile 30: set_trace_func nil 31: end
Puts option summary into to and returns to. Yields each line if a block is given.
| to: | Output destination, which must have method <<. Defaults to []. |
| width: | Width of left side, defaults to @summary_width. |
| max: | Maximum length allowed for left side, defaults to width - 1. |
| indent: | Indentation, defaults to @summary_indent. |
Source: show
# File lib/optparse.rb, line 968 968: def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk) 969: blk ||= proc {|l| to << (l.index($/, -1) ? l : l + $/)} 970: visit(:summarize, {}, {}, width, max, indent, &blk) 971: to 972: end
Source: show
# File ext/extmk.rb, line 40 40: def sysquote(x) 41: @quote ||= /human|os2|macos/ =~ (CROSS_COMPILING || RUBY_PLATFORM) 42: @quote ? x.quote : x 43: end
Marks obj as tainted—if the $SAFE level is set appropriately, many method calls which might alter the running programs environment will refuse to accept tainted strings.
Source: show
VALUE
rb_obj_taint(obj)
VALUE obj;
{
rb_secure(4);
if (!OBJ_TAINTED(obj)) {
if (OBJ_FROZEN(obj)) {
rb_error_frozen("object");
}
OBJ_TAINT(obj);
}
return obj;
}
Returns true if the object is tainted.
Source: show
VALUE
rb_obj_tainted(obj)
VALUE obj;
{
if (OBJ_TAINTED(obj))
return Qtrue;
return Qfalse;
}
Yields x to the block, and then returns x. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.
(1..10).tap {
|x| puts "original: #{x.inspect}"
}.to_a.tap {
|x| puts "array: #{x.inspect}"
}.select {|x| x%2==0}.tap {
|x| puts "evens: #{x.inspect}"
}.map {|x| x*x}.tap {
|x| puts "squares: #{x.inspect}"
}
Source: show
VALUE
rb_obj_tap(obj)
VALUE obj;
{
rb_yield(obj);
return obj;
}
Terminates option parsing. Optional parameter arg is a string pushed back to be the first non-option argument.
Source: show
# File lib/optparse.rb, line 805 805: def terminate(arg = nil) 806: self.class.terminate(arg) 807: end
Source: show
# File ext/dl/type.rb, line 84 84: def tget(t, i) 85: (t & (0x07 << (i * 3))) >> (i * 3) 86: end
Returns an array representation of obj. For objects of class Object and others that don’t explicitly override the method, the return value is an array containing self. However, this latter behavior will soon be obsolete.
self.to_a #=> -:1: warning: default `to_a' will be obsolete "hello".to_a #=> ["hello"] Time.new.to_a #=> [39, 54, 8, 9, 4, 2003, 3, 99, true, "CDT"]
Source: show
static VALUE
rb_any_to_a(obj)
VALUE obj;
{
rb_warn("default `to_a' will be obsolete");
return rb_ary_new3(1, obj);
}
Returns option summary list.
Source: show
# File lib/optparse.rb, line 983 983: def to_a; summarize(banner.to_a.dup) end
Returns Enumerable::Enumerator.new(self, method, *args).
e.g.:
str = "xyz"
enum = str.enum_for(:each_byte)
a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]
# protects an array from being modified
a = [1, 2, 3]
some_method(a.to_enum)
Source: show
static VALUE
obj_to_enum(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
{
VALUE meth = sym_each;
if (argc > 0) {
--argc;
meth = *argv++;
}
return rb_enumeratorize(obj, meth, argc, argv);
}
Returns a string representing obj. The default to_s prints the object’s class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns ``main.’‘
Source: show
VALUE
rb_any_to_s(obj)
VALUE obj;
{
const char *cname = rb_obj_classname(obj);
size_t len;
VALUE str;
len = strlen(cname)+6+16;
str = rb_str_new(0, len); /* 6:tags 16:addr */
snprintf(RSTRING(str)->ptr, len+1, "#<%s:0x%lx>", cname, obj);
RSTRING(str)->len = strlen(RSTRING(str)->ptr);
if (OBJ_TAINTED(obj)) OBJ_TAINT(str);
return str;
}
Source: show
# File lib/yaml/rubytypes.rb, line 14 14: def to_yaml( opts = {} ) 15: YAML::quick_emit( self, opts ) do |out| 16: out.map( taguri, to_yaml_style ) do |map| 17: to_yaml_properties.each do |m| 18: map.add( m[1..-1], instance_variable_get( m ) ) 19: end 20: end 21: end 22: end
Source: show
# File lib/yaml/rubytypes.rb, line 13 13: def to_yaml_properties; instance_variables.sort; end
Source: show
# File lib/yaml/rubytypes.rb, line 12 12: def to_yaml_style; end
Source: show
# File lib/optparse.rb, line 929 929: def top 930: @stack[-1] 931: end
Update the access and modification times of each FILE to the current time.
ruby -run -e touch -- [OPTION] FILE -v verbose
Source: show
# File lib/un.rb, line 210 210: def touch 211: setup do |argv, options| 212: FileUtils.touch argv, options 213: end 214: end
Source: show
# File ext/dl/type.rb, line 80 80: def tpush(t, x) 81: (t << 3)|x 82: end
Source: show
# File lib/mkmf.rb, line 873 873: def try_consttry_const(const, headers = nil, opt = "", &b) 874: const, type = *const 875: if try_compile("\#{COMMON_HEADERS}\n\#{cpp_include(headers)}\n/*top*/\ntypedef \#{type || 'int'} conftest_type;\nconftest_type conftestval = \#{type ? '' : '(int)'}\#{const};\n", opt, &b) 876: $defs.push(format("-DHAVE_CONST_%s", const.tr_cpp)) 877: true 878: else 879: false 880: end 881: end
Source: show
# File lib/mkmf.rb, line 818 818: def try_type(type, headers = nil, opt = "", &b) 819: if try_compile("\#{COMMON_HEADERS}\n\#{cpp_include(headers)}\n/*top*/\ntypedef \#{type} conftest_type;\nint conftestval[sizeof(conftest_type)?1:-1];\n", opt, &b) 820: $defs.push(format("-DHAVE_TYPE_%s", type.tr_cpp)) 821: true 822: else 823: false 824: end 825: end
Deprecated synonym for Object#class.
Source: show
VALUE
rb_obj_type(obj)
VALUE obj;
{
rb_warn("Object#type is deprecated; use Object#class");
return rb_class_real(CLASS_OF(obj));
}
Source: show
# File ext/dl/type.rb, line 109 109: def types2ctypes(types) 110: res = [] 111: types.each{|t| 112: res.push(DLTYPE[t][:ctype]) 113: } 114: res 115: end
Source: show
# File ext/dl/type.rb, line 88 88: def types2num(types) 89: res = 0x00 90: r = types.reverse 91: r.each{|t| 92: res = tpush(res,t) 93: } 94: res 95: end
Removes the taint from obj.
Source: show
VALUE
rb_obj_untaint(obj)
VALUE obj;
{
rb_secure(3);
if (OBJ_TAINTED(obj)) {
if (OBJ_FROZEN(obj)) {
rb_error_frozen("object");
}
FL_UNSET(obj, FL_TAINT);
}
return obj;
}
Returns version string from program_name, version and release.
Source: show
# File lib/optparse.rb, line 910 910: def ver 911: if v = version 912: str = "#{program_name} #{[v].join('.')}" 913: str << " (#{v})" if v = release 914: str 915: end 916: end
Version
Source: show
# File lib/optparse.rb, line 896 896: def version 897: @version || (defined?(::Version) && ::Version) 898: end
Traverses @stack, sending each element method id with args and block.
Source: show
# File lib/optparse.rb, line 1415 1415: def visit(id, *args, &block) 1416: el = nil 1417: @stack.reverse_each do |el| 1418: el.send(id, *args, &block) 1419: end 1420: nil 1421: end
Source: show
# File lib/optparse.rb, line 918 918: def warn(mesg = $!) 919: super("#{program_name}: #{mesg}") 920: end
Tests for the presence of a —with-config or —without-config option. Returns true if the with option is given, false if the without option is given, and the default value otherwise.
This can be useful for adding custom definitions, such as debug information.
Example:
if with_config("debug")
$defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG"
end
Source: show
# File lib/mkmf.rb, line 1061 1061: def with_config(config, *defaults) 1062: config = config.sub(/^--with[-_]/, '') 1063: val = arg_config("--with-"+config) do 1064: if arg_config("--without-"+config) 1065: false 1066: elsif block_given? 1067: yield(config, *defaults) 1068: else 1069: break *defaults 1070: end 1071: end 1072: case val 1073: when "yes" 1074: true 1075: when "no" 1076: false 1077: else 1078: val 1079: end 1080: end
Source: show
# File instruby.rb, line 198 198: def with_destdir(dir) 199: return dir if !$destdir or $destdir.empty? 200: dir = dir.sub(/\A\w:/, '') if File::PATH_SEPARATOR == ';' 201: $destdir + dir 202: end
Source: show
# File ext/pty/shl.rb, line 20 20: def writer 21: system "stty -echo raw" 22: begin 23: while true 24: c = STDIN.getc 25: if c == 26 then # C-z 26: $reader.raise(nil) 27: return 'Suspend' 28: end 29: $w_pty.print c.chr 30: $w_pty.flush 31: end 32: rescue 33: $reader.raise(nil) 34: return 'Exit' 35: ensure 36: system "stty echo -raw" 37: end 38: end
Removes the named instance variable from obj, returning that variable’s value.
class Dummy
attr_reader :var
def initialize
@var = 99
end
def remove
remove_instance_variable(:@var)
end
end
d = Dummy.new
d.var #=> 99
d.remove #=> 99
d.var #=> nil
Source: show
VALUE
rb_obj_remove_instance_variable(obj, name)
VALUE obj, name;
{
VALUE val = Qnil;
ID id = rb_to_id(name);
if (!OBJ_TAINTED(obj) && rb_safe_level() >= 4)
rb_raise(rb_eSecurityError, "Insecure: can't modify instance variable");
if (OBJ_FROZEN(obj)) rb_error_frozen("object");
if (!rb_is_instance_id(id)) {
rb_name_error(id, "`%s' is not allowed as an instance variable name", rb_id2name(id));
}
switch (TYPE(obj)) {
case T_OBJECT:
case T_CLASS:
case T_MODULE:
if (ROBJECT(obj)->iv_tbl && st_delete(ROBJECT(obj)->iv_tbl, (st_data_t*)&id, &val)) {
return val;
}
break;
default:
if (FL_TEST(obj, FL_EXIVAR) || rb_special_const_p(obj)) {
if (generic_ivar_remove(obj, id, &val)) {
return val;
}
}
break;
}
rb_name_error(id, "instance variable %s not defined", rb_id2name(id));
return Qnil; /* not reached */
}
Invoked as a callback whenever a singleton method is added to the receiver.
module Chatty
def Chatty.singleton_method_added(id)
puts "Adding #{id.id2name}"
end
def self.one() end
def two() end
def Chatty.three() end
end
produces:
Adding singleton_method_added Adding one Adding three
Source: show
static VALUE
rb_obj_dummy()
{
return Qnil;
}
Invoked as a callback whenever a singleton method is removed from the receiver.
module Chatty
def Chatty.singleton_method_removed(id)
puts "Removing #{id.id2name}"
end
def self.one() end
def two() end
def Chatty.three() end
class <<self
remove_method :three
remove_method :one
end
end
produces:
Removing three Removing one
Source: show
static VALUE
rb_obj_dummy()
{
return Qnil;
}
Invoked as a callback whenever a singleton method is undefined in the receiver.
module Chatty
def Chatty.singleton_method_undefined(id)
puts "Undefining #{id.id2name}"
end
def Chatty.one() end
class << self
undef_method(:one)
end
end
produces:
Undefining one
Source: show
static VALUE
rb_obj_dummy()
{
return Qnil;
}