Create a single bit bitmask.
Bit(0) #=> 1 Bit(1) #=> 2 Bit(2) #=> 4
This is equivalent to n-shift: "1 << n".
CREDIT: Thomas Sawyer CREDIT: George Moschovitis
[ + ]
# File lib/core/facets/bitmask.rb, line 100 def Bit(n) 1 << Integer(n) end
Similar to FILE and LINE, DIR provides the directory path to the current executing script.
CREDIT: Trans
[ + ]
# File lib/core/facets/kernel/__dir__.rb, line 8 def __DIR__ (/^(.+)?:\d+/ =~ caller[0]) ? File.dirname($1) : nil end
[ + ]
# File lib/core/facets/kernel/d.rb, line 3 def __HERE__ "#{__FILE__}: #{__LINE__}" end
Returns a As-functor that allows one to call any ancestor‘s method directly of the given object.
class A def x ; 1 ; end end class B < A def x ; 2 ; end end class C < B def x ; as(A).x ; end end C.new.x #=> 1
[ + ]
# File lib/core/facets/kernel/as.rb, line 22 def as(ancestor, &blk) @__as ||= {} unless r = @__as[ancestor] r = (@__as[ancestor] = As.new(self, ancestor)) end r.instance_eval(&blk) if block_given? #yield(r) if block_given? r end
Very simple convenience method to get a console reply.
ask "Are you happy?", "Yn"
On the command line one would see.
$ Are you happy? [Yn]
Responding:
$ Are you happy? [Yn] Y <ENTER>
The ask method would return "Y".
[ + ]
# File lib/core/facets/kernel/ask.rb, line 19 def ask(question, answers=nil) $stdout << "#{question}" $stdout << " [#{answers}] " if answers until inp = $stdin.gets ; sleep 1 ; end inp.strip end
Takes an array or hash with default values and creates singleton attr_accessors for each.
attr_singleton_accessor { :x => 1, :y => 2 } @x #=> 1 @y #=> 2 self.x = 3 self.y = 4 self.x #=> 3 self.y #=> 4 CREDIT: Trans
[ + ]
# File lib/core/facets/kernel/attr_singleton.rb, line 54 def attr_singleton_accessor(*args) #h, a = *args.partition{|a| Hash===a} (class << self ; self ; end).send( :attr_accessor, *args ) #(class << self ; self ; end).send( :attr_accessor, *h.keys ) #h.each { |k,v| instance_variable_set("@#{k}", v) } end
Takes an array or a hash with default values and creates singleton attr_readers for each.
attr_singleton_reader {:x => 1, :y => 2} @x #=> 1 @y #=> 2 self.x #=> 1 self.y #=> 2 CREDIT: Trans
[ + ]
# File lib/core/facets/kernel/attr_singleton.rb, line 14 def attr_singleton_reader(*args) #h, a = *args.partition{|a| Hash===a} (class << self ; self ; end).send( :attr_reader, *args ) #(class << self ; self ; end).send( :attr_reader, *h.keys ) #h.each { |k,v| instance_variable_set("@#{k}", v) } end
Takes an array or a hash with default values and creates singleton attr_writers for each.
attr_singleton_writer { :x => 1, :y => 2 } @x #=> 1 @y #=> 2 self.x = 3 self.y = 4 @x #=> 3 @y #=> 4 CREDIT: Trans
[ + ]
# File lib/core/facets/kernel/attr_singleton.rb, line 34 def attr_singleton_writer(*args) #h, a = *args.partition{|a| Hash===a} (class << self ; self ; end).send( :attr_writer, *args ) #(class << self ; self ; end).send( :attr_writer, *h.keys ) #h.each { |k,v| instance_variable_set("@#{k}", v) } end
An object is blank if it‘s nil, empty, or a whitespace string. For example, "", " ", nil, [], and {} are blank.
This simplifies
if !address.nil? && !address.empty?
to
if !address.blank?
[ + ]
# File lib/core/facets/blank.rb, line 14 def blank? respond_to?(:empty?) ? empty? : !self end
Returns true is an object is class TrueClass or FalseClass, otherwise false.
true.bool? #=> true false.bool? #=> true nil.bool? #=> false
[ + ]
# File lib/core/facets/boolean.rb, line 127 def bool? (true == self or false == self) end
Parse a caller string and break it into its components, returning an array. Returns:
For example, from irb,
call_stack(1)
produces
[["(irb)", 2, :irb_binding],
["/usr/lib/ruby/1.8/irb/workspace.rb", 52, :irb_binding], ["/usr/lib/ruby/1.8/irb/workspace.rb", 52, nil]]
Note: If the user decides to redefine caller() to output data in a different format, prior to requiring this, then the results will be indeterminate.
CREDIT: Trans
[ + ]
# File lib/core/facets/callstack.rb, line 27 def callstack( level = 1 ) call_str_array = pp_callstack(level) stack = [] call_str_array.each{ |call_str| file, lineno, method = call_str.split(':') if method =~ /in `(.*)'/ then method = $1.intern() end stack << [file, lineno.to_i, method] } stack end
Repeat loop until it yeilds false or nil.
a = [3, 2, 1] complete do b << a.pop end b #=> [3, 2, 1, nil] CREDIT: Trans
[ + ]
# File lib/core/facets/kernel/complete.rb, line 13 def complete loop { break unless yield } end
This is similar to +Module#const_get+ but is accessible at all levels, and, unlike const_get, can handle module hierarchy.
constant("Fixnum") # -> Fixnum constant(:Fixnum) # -> Fixnum constant("Process::Sys") # -> Process::Sys constant("Regexp::MULTILINE") # -> 4 require 'test/unit' Test.constant("Unit::Assertions") # -> Test::Unit::Assertions Test.constant("::Test::Unit") # -> Test::Unit CREDIT: Trans
[ + ]
# File lib/core/facets/kernel/constant.rb, line 18 def constant(const) const = const.to_s.dup base = const.sub!(/^::/, '') ? Object : ( self.kind_of?(Module) ? self : self.class ) const.split(/::/).inject(base){ |mod, name| mod.const_get(name) } end
Like p but gives file and line number.
d("hi")
produces
/home/dave/projects/foo.rb, 38 "hi"
TODO: This is borderline "prime". Keep here?
Another copy of it exits in dtools.rb
[ + ]
# File lib/core/facets/kernel/d.rb, line 19 def d(*x) puts "#{__FILE__}, #{__LINE__}" x.each{ |e| puts e.inspect } #p(*x) x.size > 1 ? x : x.last #x.last end
Anything that can be marshaled can be copied in totality. This is also commonly called a deep_copy.
"ABC".copy #=> "ABC"
[ + ]
# File lib/core/facets/kernel/deep_copy.rb, line 8 def deep_copy Marshal::load(Marshal::dump(self)) end
Forces the result of a promise to be computed (if necessary) and returns the bare result object. Once evaluated, the result of the promise will be cached. Nested promises will be evaluated together, until the first non-promise result.
If called on a value that is not a promise, it will simply return it.
[ + ]
# File lib/core/facets/lazy.rb, line 219 def demand( promise ) if promise.respond_to? :__result__ promise.__result__ else # not really a promise promise end end
For debugging and showing examples. Currently this takes an argument of a string in a block.
demo {%{ a = [1,2,3] }} demo {%{ a.slice(1,2) }} demo {%{ a.map { |x| x**3 } }}
Produces:
a = [1,2,3] #=> [1, 2, 3] a.slice(1,2) #=> [2, 3] a.map { |x| x**3 } #=> [1, 8, 27] TODO: Is there a way to do this without the eval string in block? Preferably just a block and no string.
[ + ]
# File lib/core/facets/kernel/demo.rb, line 19 def demo(out=$stdout,&block) out << sprintf("%-25s#=> %s\n", expr = block.call, eval(expr, block.binding).inspect) end
During this trying time when no one can get their techie catchwords to stick to the refrigerator no matter how hard they slap it # with the enchanted magnetic spatula, it’s good to know that the contrived phrases really do fly, graceful and unclasped and bearing north toward chilled shrimp. I know what my Hallowe’en pumpkin is going to say.
-- why the lucky stiff CREDIT: WhyTheLuckyStiff
[ + ]
# File lib/core/facets/metaid.rb, line 69 def eigenclass (class << self; self; end) end
Sets $VERBOSE to true for the duration of the block and back to its original value afterwards.
CREDIT: David Heinemeier Hansson
[ + ]
# File lib/core/facets/kernel/silence.rb, line 67 def enable_warnings old_verbose, $VERBOSE = $VERBOSE, true yield ensure $VERBOSE = old_verbose end
Yield self -or- return self.
"a".ergo.upcase #=> "A" nil.ergo.foobar #=> nil "a".ergo{ |o| o.upcase } #=> "A" nil.ergo{ |o| o.foobar } #=> nil
This is like tap, but tap yields self -and- returns self.
CREDIT: Daniel DeLorme
[ + ]
# File lib/core/facets/kernel/ergo.rb, line 17 def ergo &b if block_given? b.arity == 1 ? yield(self) : instance_eval(&b) else self end end
Returns true is an object is class FalseClass, otherwise false.
true.false? #=> false false.false? #=> true nil.false? #=> false
[ + ]
# File lib/core/facets/boolean.rb, line 116 def false? (false == self) end
Schedules a computation to be run asynchronously in a background thread and returns a promise for its result. An attempt to demand the result of the promise will block until the computation finishes.
As with Kernel.promise, this passes the block a promise for its own result. Use wisely.
[ + ]
# File lib/core/facets/lazy.rb, line 234 def future( &computation ) #:yields: result Lazy::Future.new(&computation) end
Is self included in other?
5.in?(0..10) #=> true 5.in?([0,1,2,3]) #=> false
[ + ]
# File lib/core/facets/kernel/in.rb, line 8 def in?(other) other.include?(self) end
Access internals of an object as if with private access.
class X metaclass.instance.attr_reader :x end
[ + ]
# File lib/core/facets/kernel/instance.rb, line 12 def instance @_instance_functor ||= Functor.new do |op,*args| send(op,*args) end end
Set instance variables using a hash.
instance_assign('@a'=>1, '@b'=>2) @a #=> 1 @b #=> 2
WARNING: instance_assign will be deprecated. Use instance_vars.update instead.
[ + ]
# File lib/core/facets/kernel/instance_assign.rb, line 32 def instance_assign(hash) hash.each do |k,v| k = "@#{k}" if k !~ /^@/ instance_variable_set(k, v) end return self end
Easy access to an object qua class, otherwise known as the object‘s metaclass or singleton class. This implemnetation alwasy returns the class, even if a block is provided to eval against it.
It is what it is. CREDIT: Trans
[ + ]
# File lib/core/facets/kernel/instance_class.rb, line 19 def instance_class(&block) (class << self; self; end).module_eval(&block) if block (class << self; self; end) end
Return instance variable values in an array.
class X def initialize(a,b) @a, @b = a, b end end x = X.new(1,2) x.instance_values #=> { "a"=>1, "b"=>2 }
WARNING: instance_values will be deprecated. Use instance_vars.to_hash instead.
[ + ]
# File lib/core/facets/kernel/instance_assign.rb, line 17 def instance_values instance_variables.inject({}) do |values, name| values[name[1..-1]] = instance_variable_get(name) values end end
[ + ]
# File lib/core/facets/kernel/instance_variables.rb, line 3 def instance_vars InstanceVariables.new(self) end
Load file from same dir as calling script.
load_local 'templib'
[ + ]
# File lib/core/facets/kernel/require_local.rb, line 17 def load_local(fname, safe=nil) #fdir = File.expand_path( File.dirname( caller[0] ) ) fdir = File.dirname( caller[0] ) load( File.join( fdir, fname ), safe ) end
Random generator that returns true or false. Can also take a block that has a 50/50 chance to being executed.
maybe #=> true maybe #=> false
[ + ]
# File lib/core/facets/kernel/maybe.rb, line 9 def maybe(chance = 0.5, &block) if block then yield if rand < chance else rand < chance end end
Alias a method defined in the metaclass (ie. singleton class).
def X.y?; "y?" ; end X.meta_alias "ynot?", "y?" X.ynot? #=> y? CREDIT: Trans
[ + ]
# File lib/core/facets/metaid.rb, line 11 def meta_alias(*args) meta_class do alias_method(*args) end end
[ + ]
# File lib/core/facets/metaid.rb, line 47 def meta_class(&block) if block_given? (class << self; self; end).class_eval(&block) else (class << self; self; end) end end
Add method to a meta-class —i.e. a singleton method.
class X; end X.meta_def(:x){"x"} X.x #=> "x" CREDIT: WhyTheLuckyStiff
[ + ]
# File lib/core/facets/metaid.rb, line 38 def meta_def( name, &block ) meta_class do define_method( name, &block ) end end
Evaluate code in a metaclass. This is equivalent to ‘meta_class.instance_eval’.
CREDIT: WhyTheLuckyStiff
[ + ]
# File lib/core/facets/metaid.rb, line 22 def meta_eval(str=nil, &blk) if str meta_class.instance_eval(str) else meta_class.instance_eval(&blk) end end
Alias for meta_class
The opposite of nil?.
"hello".not_nil? # -> true nil.not_nil? # -> false CREDIT: Gavin Sinclair
[ + ]
# File lib/core/facets/kernel/not_nil.rb, line 10 def not_nil? not nil? end
Returns the object id as a string in hexideciaml, which is how Ruby reports them with inspect.
"ABC".object_hexid #=> "0x402d359c"
[ + ]
# File lib/core/facets/kernel/object_hexid.rb, line 8 def object_hexid return "0x" << ('%.x' % (2*self.__id__)) #[1..-1] end
Send only to public methods.
class X private def foo; end end X.new.object_send(:foo) => NoMethodError: private method `foo' called for #<X:0xb7ac6ba8>
TODO: object_send needs to change for 1.9.
CREDIT: Trans
[ + ]
# File lib/core/facets/kernel/object_send.rb, line 20 def object_send(name,*args,&blk) #instance_eval "self.#{name}(*args)" if respond_to?(name) send(name,*args,&blk) else #if respond_to?(:method_missing) method_missing(name,*args,&blk) #else # raise NoMethodError end end
Alternate to standard p method that outputs Kernel#inspect to stdout, but also passes through the orginal argument(s).
x = 1 r = 4 + q(1) p r
produces
1 5
DEPRECATE AS OF 1.9, if p will then do this too.
[ + ]
# File lib/core/facets/kernel/p.rb, line 18 def p(*x) x.each{ |e| puts e.inspect } #p(*x) x.size > 1 ? x : x.last #x.last end
Assign via accessor methods using a hash, associative array or block.
object.populate( :a => 1, :b => 2 ) object.populate( :a, 1, :b, 2 ) object.populate( [:a, 1], [:b, 2] ) object.populate( *[[:a, 1], [:b, 2]] ) object.populate{ |s| s.a = 1; s.b = 2 }
These are all the same as doing:
object.a = 1 object.b = 2
Using an associative array instead of hash guarentees order of assignemnt.
Using a hash or array will not raise an error if the accessor does not exits —it will simply be skipped.
TODO: Better name, set_with ?
[ + ]
# File lib/core/facets/kernel/populate.rb, line 25 def populate(data=nil) #:yield: if data data.each do |k,v| send("#{k}=", v) if respond_to?("#{k}=") end end yield(self) if block_given? self end
The promise() function is used together with demand() to implement lazy evaluation. It returns a promise to evaluate the provided block at a future time. Evaluation can be demanded and the block‘s result obtained via the demand() function.
Implicit evaluation is also supported: the first message sent to it will demand evaluation, after which that message and any subsequent messages will be forwarded to the result object.
As an aid to circular programming, the block will be passed a promise for its own result when it is evaluated. Be careful not to force that promise during the computation, lest the computation diverge.
[ + ]
# File lib/core/facets/lazy.rb, line 208 def promise( &computation ) #:yields: result Lazy::Promise.new(&computation) end
Easy access to an object qua class, otherwise known as the object‘s singleton class.
Yes, another one.
CREDIT: Trans
[ + ]
# File lib/core/facets/kernel/qua_class.rb, line 10 def qua_class(&block) if block_given? (class << self; self; end).class_eval(&block) else (class << self; self; end) end end
Require a pattern of files. This make is easy to require an entire directory, for instance.
require_all 'facets/time/*'
[ + ]
# File lib/core/facets/kernel/require_all.rb, line 8 def require_all(pat) $LOAD_PATH.each do |path| fs = Dir[File.join(path,pat)] unless fs.empty? fs.each { |f| Kernel.require( f ) unless File.directory?( f ) } break; end end end
Require file from same dir as calling script.
require_local 'templib'
[ + ]
# File lib/core/facets/kernel/require_local.rb, line 7 def require_local(fname) #fdir = File.expand_path( File.dirname( caller[0] ) ) fdir = File.dirname( caller[0] ) require( File.join( fdir, fname ) ) end
Provides a shortcut to the Regexp.escape module method.
resc("H..LO") #=> "H\\.\\.LO" TODO: Should this be deprecated in favor of String#to_re/to_rx ? CREDIT: Trans
[ + ]
# File lib/core/facets/kernel/resc.rb, line 11 def resc(str) Regexp.escape(str.to_s) end
Like respond_to? but returns the result of the call if it does indeed respond.
class X def f; "f"; end end x = X.new x.respond(:f) #=> "f" x.respond(:g) #=> nil CREDIT: Trans
[ + ]
# File lib/core/facets/kernel/respond.rb, line 16 def respond(sym, *args) return nil if not respond_to?(sym) send(sym, *args) end
Alias for respond
A Ruby-ized realization of the K combinator.
returning Book.new do |book| book.title = "Imperium" book.author = "Ulick Varange" end
Technically, returning probably should force the return of the stated object irregardless of any return statements that might appear within it‘s block. This might differentiate returning from with, however it also would require implementation in Ruby itself.
CREDIT: Mikael Brockman
[ + ]
# File lib/core/facets/kernel/returning.rb, line 18 def returning(obj=self) #:yield: yield obj obj end
Call parent class/module methods once bound to self.
TODO: Does this have the proper scope for send?
[ + ]
# File lib/core/facets/kernel/as.rb, line 36 def send_as(ancestor, sym, *args, &blk) ancestor.instance_method(sym).bind(self).call(*args,&blk) end
Set setter methods using a another object.
class X attr_accessor :a, :b def initialize( a, b ) @a,@b = a,b end end obj1 = X.new( 1, 2 ) obj2 = X.new obj2.set_from(obj1) obj2.a #=> 1 obj2.b #=> 2
TODO: pepulate_from(obj) ?
[ + ]
# File lib/core/facets/kernel/populate.rb, line 54 def set_from(obj, *fields) unless fields.empty? fields.each do |k| send( "#{k}=", obj.send("#{k}") ) #if self.respond_to?("#{k}=") && obj.respond_to?("#{k}") end else setters = methods.collect { |m| m =~ /=$/ } setters.each do |setter| getter = setter.chomp('=') if obj.respond_to?(getter) send( setter, obj.send(getter) ) fields < getter end end end fields end
[ + ]
# File lib/core/facets/kernel/silence.rb, line 27 def silence_stderr #:yeild: silence_stream(STDERR) { yield } end
[ + ]
# File lib/core/facets/kernel/silence.rb, line 32 def silence_stdout #:yeild: silence_stream(STDOUT) { yield } end
Silences any stream for the duration of the block.
silence_stream(STDOUT) do puts 'This will never be seen' end puts 'But this will' CREDIT: David Heinemeier Hansson
[ + ]
# File lib/core/facets/kernel/silence.rb, line 13 def silence_stream(*streams) #:yeild: on_hold = streams.collect{ |stream| stream.dup } streams.each do |stream| stream.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null') stream.sync = true end yield ensure streams.each_with_index do |stream, i| stream.reopen(on_hold[i]) end end
Sets $VERBOSE to nil for the duration of the block and back to its original value afterwards.
silence_warnings do value = noisy_call # no warning voiced end noisy_call # no warning is voiced CREDIT: David Heinemeier Hansson
[ + ]
# File lib/core/facets/kernel/silence.rb, line 55 def silence_warnings old_verbose, $VERBOSE = $VERBOSE, nil yield ensure $VERBOSE = old_verbose end
Just like silence_stream, but will default to STDOUT, STDERR if no streams are given.
[ + ]
# File lib/core/facets/kernel/silence.rb, line 39 def silently(*streams) #:yeild: streams = [STDOUT, STDERR] if streams.empty? silence_stream(*streams){ yield } end
Alias for singleton_class
Easy access to an object‘s "special" class,
One day these names must be reconciled!
[ + ]
# File lib/core/facets/kernel/singleton_class.rb, line 7 def singleton_class(&block) if block_given? (class << self; self; end).class_eval(&block) else (class << self; self; end) end end
Like super but skips to a specific ancestor module or class.
class A def x ; 1 ; end end class B < A def x ; 2 ; end end class C < B def x ; super_as(A) ; end end C.new.x #=> 1
[ + ]
# File lib/core/facets/kernel/as.rb, line 73 def super_as(klass=self.class.superclass, *args, &blk) unless self.class.ancestors.include?(klass) raise ArgumentError end called = /\`([^\']+)\'/.match(caller(1).first)[1].to_sym klass.instance_method(called).bind(self).call(*args,&blk) end
Returns method of a parent class bound to self.
[ + ]
# File lib/core/facets/kernel/as.rb, line 50 def super_method(klass, meth) unless self.class.ancestors.include?(klass) raise ArgumentError, "Not an ancestor for super_method-- #{klass}" end klass.instance_method(meth).bind(self) end
The tap K-Combinator. This yields self -and- returns self.
[ + ]
# File lib/core/facets/kernel/tap.rb, line 7 def tap(&b) if block_given? b.arity == 1 ? yield(self) : instance_eval(&b) end self end
Boolean conversion for not being nil or false. Other classes may redefine this to suite the particular need.
"abc".to_b #=> true true.to_b #=> true false.to_b #=> false nil.to_b #=> false
[ + ]
# File lib/core/facets/boolean.rb, line 94 def to_b self ? true : false end
Returns true is an object is class TrueClass, otherwise false.
true.true? #=> true false.true? #=> false nil.true? #=> false
[ + ]
# File lib/core/facets/boolean.rb, line 105 def true? (true == self) end
Try a method.
@person ? @person.name : nil
vs
@person.try(:name) CREDIT: Chris Wanstrath
[ + ]
# File lib/core/facets/kernel/try.rb, line 10 def try(method, default=nil) if respond_to? method send method else default end end
Tests to see if something has value. An object is considered to have value if it is not nil? and if it responds to empty?, is not empty.
nil.val? #=> false [].val? #=> false 10.val? #=> true [nil].val? #=> true
[ + ]
# File lib/core/facets/kernel/val.rb, line 12 def val? return false if nil? return false if empty? if respond_to?(:empty?) true end