Class: NSObject
- Includes:
- Kernel
Overview
Direct Known Subclasses
ADInterstitialAd, ARGF, AVAsset, AVAssetExportSession, AVAssetImageGenerator, AVAssetReader, AVAssetReaderOutput, AVAssetResourceLoader, AVAssetResourceLoadingRequest, AVAssetTrack, AVAssetTrackSegment, AVAssetWriter, AVAssetWriterInput, AVAssetWriterInputPixelBufferAdaptor, AVAudioMix, AVAudioMixInputParameters, AVAudioPlayer, AVAudioRecorder, AVAudioSession, AVAudioSessionChannelDescription, AVAudioSessionDataSourceDescription, AVAudioSessionPortDescription, AVAudioSessionRouteDescription, AVCaptureAudioChannel, AVCaptureConnection, AVCaptureDevice, AVCaptureDeviceFormat, AVCaptureInput, AVCaptureInputPort, AVCaptureOutput, AVCaptureSession, AVFrameRateRange, AVMediaSelectionGroup, AVMediaSelectionOption, AVMetadataItem, AVMetadataObject, AVPlayer, AVPlayerItem, AVPlayerItemAccessLog, AVPlayerItemAccessLogEvent, AVPlayerItemErrorLog, AVPlayerItemErrorLogEvent, AVPlayerItemOutput, AVPlayerItemTrack, AVTextStyleRule, AVTimedMetadataGroup, AVVideoComposition, AVVideoCompositionCoreAnimationTool, AVVideoCompositionInstruction, AVVideoCompositionLayerInstruction, Binding, Boxed, CAAnimation, CADisplayLink, CAEmitterCell, CALayer, CAMediaTimingFunction, CATransaction, CAValueFunction, CIColor, CIContext, CIDetector, CIFeature, CIFilter, CIImage, CIVector, CLGeocoder, CLHeading, CLLocation, CLLocationManager, CLPlacemark, CLRegion, CMAttitude, CMLogItem, CMMotionManager, CTCall, CTCallCenter, CTCarrier, CTTelephonyNetworkInfo, Data, Dispatch::Object, EKEventStore, EKObject, EKRecurrenceDayOfWeek, EKRecurrenceEnd, ENV, Encoding, Encoding::Converter, Enumerable::Enumerator, Enumerator, FalseClass, File::Stat, GKAchievement, GKAchievementDescription, GKChallenge, GKChallengeEventHandler, GKInvite, GKLeaderboard, GKMatch, GKMatchRequest, GKMatchmaker, GKNotificationBanner, GKPeerPickerController, GKPlayer, GKScore, GKSession, GKTurnBasedEventHandler, GKTurnBasedMatch, GKTurnBasedParticipant, GKVoiceChat, GKVoiceChatService, IO, MKDirectionsRequest, MKMapItem, MKReverseGeocoder, MKShape, MKUserLocation, MPMediaEntity, MPMediaItemArtwork, MPMediaLibrary, MPMediaPredicate, MPMediaQuery, MPMediaQuerySection, MPMovieAccessLog, MPMovieAccessLogEvent, MPMovieErrorLog, MPMovieErrorLogEvent, MPMoviePlayerController, MPMusicPlayerController, MPNowPlayingInfoCenter, MPTimedMetadata, MatchData, Method, Module, Mutex, NKAssetDownload, NKIssue, NKLibrary, NSArray, NSAssertionHandler, NSAtomicStoreCacheNode, NSAttributedString, NSAutoreleasePool, NSBundle, NSCache, NSCachedURLResponse, NSCalendar, NSCharacterSet, NSCoder, NSCondition, NSConditionLock, NSData, NSDate, NSDateComponents, NSDecimalNumberHandler, NSDictionary, NSEntityDescription, NSEntityMapping, NSEntityMigrationPolicy, NSEnumerator, NSError, NSException, NSExpression, NSFetchedResultsController, NSFileCoordinator, NSFileHandle, NSFileManager, NSFileSecurity, NSFileVersion, NSFileWrapper, NSFormatter, NSHTTPCookie, NSHTTPCookieStorage, NSHashTable, NSIncrementalStoreNode, NSIndexPath, NSIndexSet, NSInvocation, NSJSONSerialization, NSLinguisticTagger, NSLocale, NSLock, NSManagedObject, NSManagedObjectContext, NSManagedObjectID, NSManagedObjectModel, NSMapTable, NSMappingModel, NSMergeConflict, NSMergePolicy, NSMetadataItem, NSMetadataQuery, NSMetadataQueryAttributeValueTuple, NSMetadataQueryResultGroup, NSMethodSignature, NSMigrationManager, NSNetService, NSNetServiceBrowser, NSNotification, NSNotificationCenter, NSNotificationQueue, NSNull, NSOperation, NSOperationQueue, NSOrderedSet, NSOrthography, NSParagraphStyle, NSPersistentStore, NSPersistentStoreCoordinator, NSPersistentStoreRequest, NSPipe, NSPointerArray, NSPointerFunctions, NSPort, NSPredicate, NSProcessInfo, NSPropertyDescription, NSPropertyListSerialization, NSPropertyMapping, NSProxy, NSRecursiveLock, NSRegularExpression, NSRunLoop, NSScanner, NSSet, NSShadow, NSSortDescriptor, NSStream, NSString, NSStringDrawingContext, NSThread, NSTimeZone, NSTimer, NSURL, NSURLAuthenticationChallenge, NSURLCache, NSURLConnection, NSURLCredential, NSURLCredentialStorage, NSURLProtectionSpace, NSURLProtocol, NSURLRequest, NSURLResponse, NSUUID, NSUbiquitousKeyValueStore, NSUndoManager, NSUserDefaults, NSValue, NSValueTransformer, NSXMLParser, NilClass, Object, PKPass, PKPassLibrary, Pointer, Proc, Process::GID, Process::Status, Process::Sys, Process::UID, Random, Range, Regexp, RubyObject, SKDownload, SKPayment, SKPaymentQueue, SKPaymentTransaction, SKProduct, SKProductsResponse, SKRequest, SLRequest, Struct, Thread, ThreadGroup, TopLevel, TrueClass, UIAcceleration, UIAccelerometer, UIAccessibilityElement, UIActivity, UIBarItem, UIBezierPath, UICollectionViewLayout, UICollectionViewLayoutAttributes, UICollectionViewUpdateItem, UIColor, UIDevice, UIDictationPhrase, UIDocument, UIDocumentInteractionController, UIEvent, UIFont, UIGestureRecognizer, UIImage, UIMenuItem, UINavigationItem, UINib, UIPasteboard, UIPopoverController, UIPrintFormatter, UIPrintInfo, UIPrintInteractionController, UIPrintPaper, UIResponder, UIScreen, UIScreenMode, UISearchDisplayController, UIStoryboard, UIStoryboardSegue, UITextChecker, UITextInputMode, UITextInputStringTokenizer, UITextPosition, UITextRange, UITextSelectionRect, UITouch, UnboundMethod
Class Method Summary (collapse)
-
+ `
Returns the standard output of running cmd in a subshell.
-
+ alloc
Returns a new instance of the receiving class.
-
+ allocWithZone:
Returns a new instance of the receiving class.
- + autoload
-
+ autoload?
Returns filename to be loaded if name is registered as autoload.
-
+ autorelease_pool { ... }
autorelease_pool provides memory management funtion like @autoreleasepool in ARC.
-
+ binding
Returns a Binding object, describing the variable and method bindings at the point of call.
-
+ block_given?
Returns true if yield would execute a block in the current context.
-
+ caller
Returns the current execution stack---an array containing strings in the form "file:line" or "file:line: in `method'".
-
+ cancelPreviousPerformRequestsWithTarget:
Cancels perform requests previously registered with the performSelector:withObject:afterDelay: instance method.
-
+ cancelPreviousPerformRequestsWithTarget:selector:object:
Cancels perform requests previously registered with performSelector:withObject:afterDelay:.
-
+ catch {|tag| ... }
catch executes its block.
-
+ class
Returns the class object.
-
+ classFallbacksForKeyedArchiver
Overridden to return the names of classes that can be used to decode objects if their class is unavailable.
-
+ classForKeyedUnarchiver
Overridden by subclasses to substitute a new class during keyed unarchiving.
-
+ conformsToProtocol:
Returns a Boolean value that indicates whether the receiver conforms to a given protocol.
-
+ copyWithZone:
Returns the receiver.
-
+ description
Returns a string that represents the contents of the receiving class.
-
+ display
Prints obj on the given port (default $>).
-
+ fail
With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil.
-
+ format
Returns the string resulting from applying format_string to any additional arguments.
-
+ framework
Loads a framework which specified a framework_name.
-
+ getpass
Displays a prompt which passed prompt as String to /dev/tty, and returns a string which read a password from /dev/tty.
-
+ gets
Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line.
-
+ global_variables
Returns an array of the names of global variables.
-
+ initialize
Initializes the receiver before it’s used (before it receives its first message).
-
+ instanceMethodForSelector:
Locates and returns the address of the implementation of the instance method identified by a given selector.
-
+ instanceMethodSignatureForSelector:
Returns an NSMethodSignature object that contains a description of the instance method identified by a given selector.
-
+ instancesRespondToSelector:
Returns a Boolean value that indicates whether instances of the receiver are capable of responding to a given selector.
-
+ isSubclassOfClass:
Returns a Boolean value that indicates whether the receiving class is a subclass of, or identical to, a given class.
-
+ iterator?
Returns true if yield would execute a block in the current context.
- + lambda {|...| ... }
-
+ load
Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading.
-
+ load_bridge_support_file
Loads a Bridge Support in the file filename.
-
+ load_plist
Returns a ruby object which is converted from string of plist format.
-
+ local_variables
Returns the names of the current local variables.
-
+ loop
Repeatedly executes the block.
-
+ mutableCopyWithZone:
Returns the receiver.
-
+ new
Allocates a new instance of the receiving class, sends it an init message, and returns the initialized object.
-
+ open
Creates an IO object connected to the given stream, file, or subprocess.
-
+ p
For each object, directly writes obj.inspect followed by the current output record separator to the program's standard output.
-
+ print
Prints each object in turn to $stdout.
-
+ printf
Equivalent to:.
-
+ proc {|...| ... }
Equivalent to Proc.new.
-
+ putc
Equivalent to:.
-
+ puts
Equivalent to.
-
+ raise
With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil.
-
+ rand
If max is Range, returns a pseudorandom number where range.member(number) == true.
- + readline
-
+ readlines
Returns an array containing the lines returned by calling Kernel.gets(sep) until the end of file.
-
+ require
Loads the given name, returning true if successful and false if the feature is already loaded.
-
+ resolveClassMethod:
Dynamically provides an implementation for a given selector for a class method.
-
+ resolveInstanceMethod:
Dynamically provides an implementation for a given selector for an instance method.
- + select
-
+ setVersion:
Sets the receiver's version number.
-
+ sprintf
Returns the string resulting from applying format_string to any additional arguments.
-
+ srand
Seeds the pseudorandom number generator to the value of number.
-
+ superclass
Returns the class object for the receiver’s superclass.
-
+ test
Uses the integer aCmd to perform various tests on file1 (first table below) or on file1 and file2 (second table).
-
+ throw
Transfers control to the end of the active catch block waiting for tag.
-
+ trace_var
Controls tracing of assignments to global variables.
-
+ trap
Specifies the handling of signals.
-
+ untrace_var
Removes tracing for the specified command on the given global variable and returns nil.
-
+ version
Returns the version number assigned to the class.
Instance Method Summary (collapse)
-
- !
Boolean negate.
-
- !=
Returns true if two objects are not-equal, otherwise false.
-
- !~
Returns true if two objects do not match (using the =~ method), otherwise false.
-
- <=>
Returns 0 if obj === other, otherwise nil.
-
- ==
Equality---At the Object level, == returns true only if obj and other are the same object.
-
- ===
Case Equality---For class Object, effectively the same as calling #==, but typically overridden by descendants to provide meaningful semantics in case statements.
- - =~
-
- __callee__
Returns the name of the current method as a Symbol.
-
- __method__
Returns the name of the current method as a Symbol.
-
- __send__
Invokes the method identified by symbol, passing it any arguments specified.
-
- __type__
:nodoc:.
-
- autoContentAccessingProxy
Creates and returns a proxy for the receiving object This method creates and returns a proxy for the receiving object, if the receiver adopts the NSDiscardableContent protocol and still has undiscarded content.The proxy calls beginContentAccess on the receiver to keep the content available as long as the proxy lives, and calls endContentAccess when the proxy is deallocated.The wrapper object is otherwise a subclass of NSProxy and forwards messages to the original receiver object as an NSProxy does.
-
- awakeAfterUsingCoder:
Overridden by subclasses to substitute another object in place of the object that was decoded and subsequently received this message.
-
- classForCoder
Overridden by subclasses to substitute a class other than its own during coding.
-
- classForKeyedArchiver
Overridden by subclasses to substitute a new class for instances during keyed archiving.
-
- clone
Produces a shallow copy of obj---the instance variables of obj are copied, but not the objects they reference.
-
- copy
Returns the object returned by copyWithZone:.
-
- dealloc
Deallocates the memory occupied by the receiver.
-
- define_singleton_method
Defines a singleton method in the receiver.
-
- doesNotRecognizeSelector:
Handles messages the receiver doesn’t recognize.
-
- dup
Produces a shallow copy of obj---the instance variables of obj are copied, but not the objects they reference.
-
- enum_for
Creates a new Enumerator which will enumerate by on calling method on obj.
-
- eql?
Equality---At the Object level, == returns true only if obj and other are the same object.
-
- equal?
Equality---At the Object level, == returns true only if obj and other are the same object.
-
- extend
Adds to obj the instance methods from each module given as a parameter.
-
- finalize
The garbage collector invokes this method on the receiver before disposing of the memory it uses.
-
- forwardingTargetForSelector:
Returns the object to which unrecognized messages should first be directed.
-
- forwardInvocation:
Overridden by subclasses to forward messages to other objects.
-
- freeze
Prevents further modifications to obj.
-
- frozen?
Returns the freeze status of obj.
-
- init
Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.
-
- initialize_clone
:nodoc:.
-
- initialize_copy
:nodoc:.
-
- initialize_dup
:nodoc:.
-
- inspect
Returns a string containing a human-readable representation of obj.
-
- instance_eval
Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj).
-
- instance_exec {|var...| ... }
Executes the given block within the context of the receiver (obj).
-
- instance_of?
Returns true if obj is an instance of the given class.
-
- instance_variable_defined?
Returns true if the given instance variable is defined in obj.
-
- instance_variable_get
Returns the value of the given instance variable, or nil if the instance variable is not set.
-
- instance_variable_set
Sets the instance variable names by symbol to object, thereby frustrating the efforts of the class's author to attempt to provide proper encapsulation.
-
- instance_variables
Returns an array of instance variable names for the receiver.
-
- is_a?
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.
-
- kind_of?
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.
- - method
-
- methodForSelector:
Locates and returns the address of the receiver’s implementation of a method so it can be called as a function.
-
- methods
Returns a list of the names of public and protected methods of obj.
-
- methodSignatureForSelector:
Returns an NSMethodSignature object that contains a description of the method identified by a given selector.
-
- mutableCopy
Returns the object returned by mutableCopyWithZone: where the zone is nil.
-
- nil?
call_seq:.
-
- performSelector:onThread:withObject:waitUntilDone:
Invokes a method of the receiver on the specified thread using the default mode.
-
- performSelector:onThread:withObject:waitUntilDone:modes:
Invokes a method of the receiver on the specified thread using the specified modes.
-
- performSelector:withObject:afterDelay:
Invokes a method of the receiver on the current thread using the default mode after a delay.
-
- performSelector:withObject:afterDelay:inModes:
Invokes a method of the receiver on the current thread using the specified modes after a delay.
-
- performSelectorInBackground:withObject:
Invokes a method of the receiver on a new background thread.
-
- performSelectorOnMainThread:withObject:waitUntilDone:
Invokes a method of the receiver on the main thread using the default mode.
-
- performSelectorOnMainThread:withObject:waitUntilDone:modes:
Invokes a method of the receiver on the main thread using the specified modes.
-
- private_methods
Returns the list of private methods accessible to obj.
-
- protected_methods
Returns the list of protected methods accessible to obj.
-
- public_method
Similar to method, searches public method only.
-
- public_methods
Returns the list of public methods accessible to obj.
-
- public_send
Invokes the method identified by symbol, passing it any arguments specified.
-
- Rational
Returns x/y;.
-
- replacementObjectForCoder:
Overridden by subclasses to substitute another object for itself during encoding.
-
- replacementObjectForKeyedArchiver:
Overridden by subclasses to substitute another object for itself during keyed archiving.
-
- respond_to?
Returns true if obj responds to the given method.
-
- respond_to_missing?
Hook method to return whether the obj can respond to id method or not.
-
- send
Invokes the method identified by symbol, passing it any arguments specified.
-
- singleton_methods
Returns an array of the names of singleton methods for obj.
-
- taint
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.
-
- tainted?
Returns true if the object is tainted.
-
- tap {|x| ... }
Yields x to the block, and then returns x.
-
- to_plist
Returns a string of plist format which is converted from Object.
-
- to_s
Returns a string representing obj.
-
- trust
Removes the untrusted mark from obj.
-
- untaint
Removes the taint from obj.
-
- untrust
Marks obj as untrusted.
-
- untrusted?
Returns true if the object is untrusted.
Constructor Details
+ (Object) initialize
Initializes the receiver before it’s used (before it receives its first message). The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
- (Object) method_missing(symbol[, *args]) (private)
Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior. If it is decided that a particular method should not be handled, then super should be called, so that ancestors can pick up the missing method. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values.
class Roman
def roman_to_int(str)
# ...
end
def method_missing(methId)
str = methId.id2name
roman_to_int(str)
end
end
r = Roman.new
r.iv #=> 4
r.xxiii #=> 23
r.mm #=> 2000
Class Method Details
+ (String) `
Returns the standard output of running cmd in a subshell. The built-in syntax %x{...} uses this method. Sets $? to the process status.
`date` #=> "Wed Apr 9 08:56:30 CDT 2003\n"
`ls testdir`.split[1] #=> "main.rb"
`echo oops && exit 99` #=> "oops\n"
$?.exitstatus #=> 99
+ (Object) alloc
Returns a new instance of the receiving class. The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to 0. You must use an init... method to complete the initialization process. For example: Do not override alloc to include initialization code. Instead, implement class-specific versions of init... methods.For historical reasons, alloc invokes allocWithZone:.
+ (Object) allocWithZone(zone)
Returns a new instance of the receiving class. The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to 0. You must use an init... method to complete the initialization process. For example: Do not override allocWithZone: to include any initialization code. Instead, class-specific versions of init... methods.This method exists for historical reasons; memory zones are no longer used by Objective-C.
+ (nil) autoload
+ (String?) autoload?(name)
Returns filename to be loaded if name is registered as autoload.
autoload(:B, "b")
autoload?(:B) #=> "b"
+ (Object) autorelease_pool { ... }
autorelease_pool provides memory management funtion like @autoreleasepool in ARC. At the end of the autorelease_pool block, object receives a release message.
str = nil
autorelease_pool {
str = "hello"
}
puts str # str has been already released. So, this line will cause crash.
+ (Binding) binding
Returns a Binding object, describing the variable and method bindings at the point of call. This object can be used when calling eval to execute the evaluated command in this environment. See also the description of class Binding.
def get_binding(param)
return binding
end
b = get_binding("hello")
eval("param", b) #=> "hello"
+ (Boolean) block_given? + (Boolean) iterator?
Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.
def try
if block_given?
yield
else
"no block"
end
end
try #=> "no block"
try { "hello" } #=> "hello"
try do "hello" end #=> "hello"
+ (Array?) caller(start = 1)
Returns the current execution stack---an array containing strings in the form "file:line" or "file:line: in `method'". The optional start parameter determines the number of initial stack entries to omit from the result.
Returns nil if start is greater than the size of current execution stack.
def a(skip)
caller(skip)
end
def b(skip)
a(skip)
end
def c(skip)
b(skip)
end
c(0) #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10:in `<main>'"]
c(1) #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11:in `<main>'"]
c(2) #=> ["prog:8:in `c'", "prog:12:in `<main>'"]
c(3) #=> ["prog:13:in `<main>'"]
c(4) #=> []
c(5) #=> nil
+ (Object) cancelPreviousPerformRequestsWithTarget(aTarget)
Cancels perform requests previously registered with the performSelector:withObject:afterDelay: instance method. All perform requests having the same target aTarget are canceled. This method removes perform requests only in the current run loop, not all run loops.
+ (Object) cancelPreviousPerformRequestsWithTarget(aTarget, selector:aSelector, object:anArgument)
Cancels perform requests previously registered with performSelector:withObject:afterDelay:. All perform requests are canceled that have the same target as aTarget, argument as anArgument, and selector as aSelector. This method removes perform requests only in the current run loop, not all run loops.
+ (Object) catch([arg]) {|tag| ... }
catch executes its block. If a throw is executed, Ruby searches up its stack for a catch block with a tag corresponding to the throw's tag. If found, that block is terminated, and catch returns the value given to throw. If throw is not called, the block terminates normally, and the value of catch is the value of the last expression evaluated. catch expressions may be nested, and the throw call need not be in lexical scope.
def routine(n)
puts n
throw :done if n <= 0
routine(n-1)
end
catch(:done) { routine(3) }
produces:
3
2
1
0
when arg is given, catch yields it as is, or when no arg is given, catch assigns a new unique object to throw. this is useful for nested catch. arg can be an arbitrary object, not only Symbol.
+ (Class) class
Returns the class object. Refer to a class only by its name when it is the receiver of a message. In all other cases, the class object must be obtained through this or a similar method. For example, here SomeClass is passed as an argument to the isKindOfClass: method (declared in the NSObject protocol):
+ (Array) classFallbacksForKeyedArchiver
Overridden to return the names of classes that can be used to decode objects if their class is unavailable. NSKeyedArchiver calls this method and stores the result inside the archive. If the actual class of an object doesn’t exist at the time of unarchiving, NSKeyedUnarchiver goes through the stored list of classes and uses the first one that does exists as a substitute class for decoding the object. The default implementation of this method returns nil.You can use this method if you introduce a new class into your application to provide some backwards compatibility in case the archive will be read on a system that does not have that class. Sometimes there may be another class which may work nearly as well as a substitute for the new class, and the archive keys and archived state for the new class can be carefully chosen (or compatibility written out) so that the object can be unarchived as the substitute class if necessary.
+ (Class) classForKeyedUnarchiver
Overridden by subclasses to substitute a new class during keyed unarchiving. During keyed unarchiving, instances of the receiver will be decoded as members of the returned class. This method overrides the results of the decoder’s class and instance name to class encoding tables.
+ (Boolean) conformsToProtocol(aProtocol)
Returns a Boolean value that indicates whether the receiver conforms to a given protocol. A class is said to “conform to” a protocol if it adopts the protocol or inherits from another class that adopts it. Protocols are adopted by listing them within angle brackets after the interface declaration. For example, here MyClass adopts the (fictitious) AffiliationRequests and Normalization protocols: A class also conforms to any protocols that are incorporated in the protocols it adopts or inherits. Protocols incorporate other protocols in the same way classes adopt them. For example, here the AffiliationRequests protocol incorporates the Joining protocol: If a class adopts a protocol that incorporates another protocol, it must also implement all the methods in the incorporated protocol or inherit those methods from a class that adopts it.This method determines conformance solely on the basis of the formal declarations in header files, as illustrated above. It doesn’t check to see whether the methods declared in the protocol are actually implemented—that’s the programmer’s responsibility.The protocol required as this method’s argument can be specified using the @protocol() directive:
+ (Object) copyWithZone(zone)
Returns the receiver. This method exists so class objects can be used in situations where you need an object that conforms to the NSCopying protocol. For example, this method lets you use a class object as a key to an NSDictionary object. You should not override this method.
+ (String) description
Returns a string that represents the contents of the receiving class. The debugger’s print-object command invokes this method to produce a textual description of an object.NSObject’s implementation of this method simply prints the name of the class.
+ (nil) display(port = $>)
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
+ (Object) raise + (Object) raise(string) + (Object) raise(exception[, string [, array]]) + (Object) fail + (Object) fail(string) + (Object) fail(exception[, string [, array]])
With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.
raise "Failed to create socket"
raise ArgumentError, "No parameters", caller
+ (String) format(format_string[, arguments...]) + (String) sprintf(format_string[, arguments...])
Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result.
The syntax of a format sequence is follows.
%[flags][width][.precision]type
A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation.
The field type characters are:
Field | Integer Format
------+--------------------------------------------------------------
b | Convert argument as a binary number.
| Negative numbers will be displayed as a two's complement
| prefixed with `..1'.
B | Equivalent to `b', but uses an uppercase 0B for prefix
| in the alternative format by #.
d | Convert argument as a decimal number.
i | Identical to `d'.
o | Convert argument as an octal number.
| Negative numbers will be displayed as a two's complement
| prefixed with `..7'.
u | Identical to `d'.
x | Convert argument as a hexadecimal number.
| Negative numbers will be displayed as a two's complement
| prefixed with `..f' (representing an infinite string of
| leading 'ff's).
X | Equivalent to `x', but uses uppercase letters.
Field | Float Format
------+--------------------------------------------------------------
e | Convert floating point argument into exponential notation
| with one digit before the decimal point as [-]d.dddddde[+-]dd.
| The precision specifies the number of digits after the decimal
| point (defaulting to six).
E | Equivalent to `e', but uses an uppercase E to indicate
| the exponent.
f | Convert floating point argument as [-]ddd.dddddd,
| where the precision specifies the number of digits after
| the decimal point.
g | Convert a floating point number using exponential form
| if the exponent is less than -4 or greater than or
| equal to the precision, or in dd.dddd form otherwise.
| The precision specifies the number of significant digits.
G | Equivalent to `g', but use an uppercase `E' in exponent form.
a | Convert floating point argument as [-]0xh.hhhhp[+-]dd,
| which is consisted from optional sign, "0x", fraction part
| as hexadecimal, "p", and exponential part as decimal.
A | Equivalent to `a', but use uppercase `X' and `P'.
Field | Other Format
------+--------------------------------------------------------------
c | Argument is the numeric code for a single character or
| a single character string itself.
p | The valuing of argument.inspect.
s | Argument is a string to be substituted. If the format
| sequence contains a precision, at most that many characters
| will be copied.
% | A percent sign itself will be displayed. No argument taken.
The flags modifies the behavior of the formats. The flag characters are:
Flag | Applies to | Meaning
---------+---------------+-----------------------------------------
space | bBdiouxX | Leave a space at the start of
| aAeEfgG | non-negative numbers.
| (numeric fmt) | For `o', `x', `X', `b' and `B', use
| | a minus sign with absolute value for
| | negative values.
---------+---------------+-----------------------------------------
(digit)$ | all | Specifies the absolute argument number
| | for this field. Absolute and relative
| | argument numbers cannot be mixed in a
| | sprintf string.
---------+---------------+-----------------------------------------
# | bBoxX | Use an alternative format.
| aAeEfgG | For the conversions `o', increase the precision
| | until the first digit will be `0' if
| | it is not formatted as complements.
| | For the conversions `x', `X', `b' and `B'
| | on non-zero, prefix the result with ``0x'',
| | ``0X'', ``0b'' and ``0B'', respectively.
| | For `a', `A', `e', `E', `f', `g', and 'G',
| | force a decimal point to be added,
| | even if no digits follow.
| | For `g' and 'G', do not remove trailing zeros.
---------+---------------+-----------------------------------------
+ | bBdiouxX | Add a leading plus sign to non-negative
| aAeEfgG | numbers.
| (numeric fmt) | For `o', `x', `X', `b' and `B', use
| | a minus sign with absolute value for
| | negative values.
---------+---------------+-----------------------------------------
- | all | Left-justify the result of this conversion.
---------+---------------+-----------------------------------------
0 (zero) | bBdiouxX | Pad with zeros, not spaces.
| aAeEfgG | For `o', `x', `X', `b' and `B', radix-1
| (numeric fmt) | is used for negative numbers formatted as
| | complements.
---------+---------------+-----------------------------------------
* | all | Use the next argument as the field width.
| | If negative, left-justify the result. If the
| | asterisk is followed by a number and a dollar
| | sign, use the indicated argument as the width.
Examples of flags:
# `+' and space flag specifies the sign of non-negative numbers.
sprintf("%d", 123) #=> "123"
sprintf("%+d", 123) #=> "+123"
sprintf("% d", 123) #=> " 123"
# `#' flag for `o' increases number of digits to show `0'.
# `+' and space flag changes format of negative numbers.
sprintf("%o", 123) #=> "173"
sprintf("%#o", 123) #=> "0173"
sprintf("%+o", -123) #=> "-173"
sprintf("%o", -123) #=> "..7605"
sprintf("%#o", -123) #=> "..7605"
# `#' flag for `x' add a prefix `0x' for non-zero numbers.
# `+' and space flag disables complements for negative numbers.
sprintf("%x", 123) #=> "7b"
sprintf("%#x", 123) #=> "0x7b"
sprintf("%+x", -123) #=> "-7b"
sprintf("%x", -123) #=> "..f85"
sprintf("%#x", -123) #=> "0x..f85"
sprintf("%#x", 0) #=> "0"
# `#' for `X' uses the prefix `0X'.
sprintf("%X", 123) #=> "7B"
sprintf("%#X", 123) #=> "0X7B"
# `#' flag for `b' add a prefix `0b' for non-zero numbers.
# `+' and space flag disables complements for negative numbers.
sprintf("%b", 123) #=> "1111011"
sprintf("%#b", 123) #=> "0b1111011"
sprintf("%+b", -123) #=> "-1111011"
sprintf("%b", -123) #=> "..10000101"
sprintf("%#b", -123) #=> "0b..10000101"
sprintf("%#b", 0) #=> "0"
# `#' for `B' uses the prefix `0B'.
sprintf("%B", 123) #=> "1111011"
sprintf("%#B", 123) #=> "0B1111011"
# `#' for `e' forces to show the decimal point.
sprintf("%.0e", 1) #=> "1e+00"
sprintf("%#.0e", 1) #=> "1.e+00"
# `#' for `f' forces to show the decimal point.
sprintf("%.0f", 1234) #=> "1234"
sprintf("%#.0f", 1234) #=> "1234."
# `#' for `g' forces to show the decimal point.
# It also disables stripping lowest zeros.
sprintf("%g", 123.4) #=> "123.4"
sprintf("%#g", 123.4) #=> "123.400"
sprintf("%g", 123456) #=> "123456"
sprintf("%#g", 123456) #=> "123456."
The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field.
Examples of width:
# padding is done by spaces, width=20
# 0 or radix-1. <------------------>
sprintf("%20d", 123) #=> " 123"
sprintf("%+20d", 123) #=> " +123"
sprintf("%020d", 123) #=> "00000000000000000123"
sprintf("%+020d", 123) #=> "+0000000000000000123"
sprintf("% 020d", 123) #=> " 0000000000000000123"
sprintf("%-20d", 123) #=> "123 "
sprintf("%-+20d", 123) #=> "+123 "
sprintf("%- 20d", 123) #=> " 123 "
sprintf("%020x", -123) #=> "..ffffffffffffffff85"
For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.)
Examples of precisions:
# precision for `d', 'o', 'x' and 'b' is
# minimum number of digits <------>
sprintf("%20.8d", 123) #=> " 00000123"
sprintf("%20.8o", 123) #=> " 00000173"
sprintf("%20.8x", 123) #=> " 0000007b"
sprintf("%20.8b", 123) #=> " 01111011"
sprintf("%20.8d", -123) #=> " -00000123"
sprintf("%20.8o", -123) #=> " ..777605"
sprintf("%20.8x", -123) #=> " ..ffff85"
sprintf("%20.8b", -11) #=> " ..110101"
# "0x" and "0b" for `#x' and `#b' is not counted for
# precision but "0" for `#o' is counted. <------>
sprintf("%#20.8d", 123) #=> " 00000123"
sprintf("%#20.8o", 123) #=> " 00000173"
sprintf("%#20.8x", 123) #=> " 0x0000007b"
sprintf("%#20.8b", 123) #=> " 0b01111011"
sprintf("%#20.8d", -123) #=> " -00000123"
sprintf("%#20.8o", -123) #=> " ..777605"
sprintf("%#20.8x", -123) #=> " 0x..ffff85"
sprintf("%#20.8b", -11) #=> " 0b..110101"
# precision for `e' is number of
# digits after the decimal point <------>
sprintf("%20.8e", 1234.56789) #=> " 1.23456789e+03"
# precision for `f' is number of
# digits after the decimal point <------>
sprintf("%20.8f", 1234.56789) #=> " 1234.56789000"
# precision for `g' is number of
# significant digits <------->
sprintf("%20.8g", 1234.56789) #=> " 1234.5679"
# <------->
sprintf("%20.8g", 123456789) #=> " 1.2345679e+08"
# precision for `s' is
# maximum number of characters <------>
sprintf("%20.8s", "string test") #=> " string t"
Examples:
sprintf("%d %04x", 123, 123) #=> "123 007b"
sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'"
sprintf("%1$*2$s %2$d %1$s", "hello", 8) #=> " hello 8 hello"
sprintf("%1$*2$s %2$d", "hello", -8) #=> "hello -8"
sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> "+1.23: 1.23:1.23"
sprintf("%u", -123) #=> "-123"
For more complex formatting, Ruby supports a reference by name.
%
Exapmles:
sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 })
#=> 1 : 2.000000
sprintf("%{foo}f", { :foo => 1 })
# => "1f"
+ (Boolean) framework(framework_name)
Loads a framework which specified a framework_name. Returns a true if loaded a framework. Otherwise, returns a false.
framework 'Foundation'
+ (String) getpass(prompt)
Displays a prompt which passed prompt as String to /dev/tty, and returns a string which read a password from /dev/tty.
+ (String?) gets(sep = $/) + (String?) gets(limit) + (String?) gets(sep, limit)
Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line. Returns nil at end of file. The optional argument specifies the record separator. The separator is included with the contents of each record. A separator of nil reads the entire contents, and a zero-length separator reads the input one paragraph at a time, where paragraphs are divided by two consecutive newlines. If the first argument is an integer, or optional second argument is given, the returning string would not be longer than the given value in bytes. If multiple filenames are present in ARGV, gets(nil) will read the contents one file at a time.
ARGV << "testfile"
print while gets
produces:
This is line one
This is line two
This is line three
And so on...
The style of programming using $_ as an implicit parameter is gradually losing favor in the Ruby community.
+ (Array) global_variables
Returns an array of the names of global variables.
global_variables.grep /std/ #=> [:$stdin, :$stdout, :$stderr]
+ (Object) initialize
Initializes the receiver before it’s used (before it receives its first message). The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.
+ (IMP) instanceMethodForSelector(aSelector)
Locates and returns the address of the implementation of the instance method identified by a given selector. An error is generated if instances of the receiver can’t respond to aSelector messages.Use this method to ask the class object for the implementation of instance methods only. To ask the class for the implementation of a class method, send the methodForSelector: instance method to the class instead.
+ (NSMethodSignature) instanceMethodSignatureForSelector(aSelector)
Returns an NSMethodSignature object that contains a description of the instance method identified by a given selector.
+ (Boolean) instancesRespondToSelector(aSelector)
Returns a Boolean value that indicates whether instances of the receiver are capable of responding to a given selector. If aSelector messages are forwarded to other objects, instances of the class are able to receive those messages without error even though this method returns NO.To ask the class whether it, rather than its instances, can respond to a particular message, send to the class instead the NSObject protocol instance method respondsToSelector:.
+ (Boolean) isSubclassOfClass(aClass)
Returns a Boolean value that indicates whether the receiving class is a subclass of, or identical to, a given class.
+ (Boolean) block_given? + (Boolean) iterator?
Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.
def try
if block_given?
yield
else
"no block"
end
end
try #=> "no block"
try { "hello" } #=> "hello"
try do "hello" end #=> "hello"
+ (Proc) lambda {|...| ... }
+ (Object) load
Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading. The load message is sent to classes and categories that are both dynamically loaded and statically linked, but only if the newly loaded class or category implements a method that can respond.The order of initialization is as follows:All initializers in any framework you link to.All +load methods in your image.All C++ static initializers and C/C++ __attribute__(constructor) functions in your image.All initializers in frameworks that link to you.In addition:A class’s +load method is called after all of its superclasses’ load methods.A category load method is called after the class’s own +load method.In a custom implementation of load you can therefore safely message other unrelated classes from the same image, but any load methods implemented by those classes may not have run yet.
+ (Object) load_bridge_support_file(filename)
Loads a Bridge Support in the file filename.
Bridge Support is an FFI interface that MacRuby uses to provide a native interface for some C functions, structures and constants.
+ (Object) load_plist(string)
Returns a ruby object which is converted from string of plist format.
data = File.read('info.plist')
load_plist(data) #=> {"CFBundleName"=>"${PRODUCT_NAME}", .... }
+ (Array) local_variables
Returns the names of the current local variables.
fred = 1
for i in 1..10
# ...
end
local_variables #=> [:fred, :i]
+ (Object) loop { ... } + (Enumerator) loop
Repeatedly executes the block.
If no block is given, an enumerator is returned instead.
loop do
print "Input: "
line = gets
break if !line or line =~ /^qQ/
# ...
end
StopIteration raised in the block breaks the loop.
+ (Object) mutableCopyWithZone(zone)
Returns the receiver. This method exists so class objects can be used in situations where you need an object that conforms to the NSMutableCopying protocol. For example, this method lets you use a class object as a key to an NSDictionary object. You should not override this method.
+ (Object) new
Allocates a new instance of the receiving class, sends it an init message, and returns the initialized object. This method is a combination of alloc and init. Like alloc, it initializes the isa instance variable of the new object so it points to the class data structure. It then invokes the init method to complete the initialization process.
+ (IO?) open(path[, mode_enc [, perm]]) + (Object) open(path[, mode_enc [, perm]]) {|io| ... }
Creates an IO object connected to the given stream, file, or subprocess.
If path does not start with a pipe character ("|"), treat it as the name of a file to open using the specified mode (defaulting to "r").
The mode_enc is either a string or an integer. If it is an integer, it must be bitwise-or of open(2) flags, such as File::RDWR or File::EXCL. If it is a string, it is either "mode", "mode:ext_enc", or "mode:ext_enc:int_enc". The mode is one of the following:
r: read (default)
w: write
a: append
The mode can be followed by "b" (means binary-mode), or "+" (means both reading and writing allowed) or both. If ext_enc (external encoding) is specified, read string will be tagged by the encoding in reading, and output string will be converted to the specified encoding in writing. If two encoding names, ext_enc and int_enc (external encoding and internal encoding), are specified, the read string is converted from ext_enc to int_enc then tagged with the int_enc in read mode, and in write mode, the output string will be converted from int_enc to ext_enc before writing.
If a file is being created, its initial permissions may be set using the integer third parameter.
If a block is specified, it will be invoked with the File object as a parameter, and the file will be automatically closed when the block terminates. The call returns the value of the block.
If path starts with a pipe character, a subprocess is created, connected to the caller by a pair of pipes. The returned IO object may be used to write to the standard input and read from the standard output of this subprocess. If the command following the "|" is a single minus sign, Ruby forks, and this subprocess is connected to the parent. In the subprocess, the open call returns nil. If the command is not "-", the subprocess runs the command. If a block is associated with an open("|-") call, that block will be run twice---once in the parent and once in the child. The block parameter will be an IO object in the parent and nil in the child. The parent's IO object will be connected to the child's $stdin and $stdout. The subprocess will be terminated at the end of the block.
open("testfile") do |f|
print f.gets
end
produces:
This is line one
Open a subprocess and read its output:
cmd = open("|date")
print cmd.gets
cmd.close
produces:
Wed Apr 9 08:56:31 CDT 2003
Open a subprocess running the same Ruby program:
f = open("|-", "w+")
if f == nil
puts "in Child"
exit
else
puts "Got: #{f.gets}"
end
produces:
Got: in Child
Open a subprocess using a block to receive the I/O object:
open("|-") do |f|
if f == nil
puts "in Child"
else
puts "Got: #{f.gets}"
end
end
produces:
Got: in Child
+ (Object) p(obj) + (Array) p(obj1, obj2, ...) + (nil) p
For each object, directly writes obj.inspect followed by the current output record separator to the program's standard output.
S = Struct.new(:name, :state)
s = S['dave', 'TX']
p s
produces:
#<S name="dave", state="TX">
+ (nil) print(obj, ...)
Prints each object in turn to $stdout. If the output field
separator ($,) is not nil, its contents will appear
between each field. If the output record separator ($\) is
not nil, it will be appended to the output. If no arguments are given,
prints $_. Objects that aren't strings will be converted
by calling their to_s method.
print "cat", [1,2,3], 99, "\n"
$, = ", "
$\ = "\n"
print "cat", [1,2,3], 99
produces:
cat12399
cat, 1, 2, 3, 99
+ (nil) printf(io, string[, obj ... ]) + (nil) printf(string[, obj ... ])
Equivalent to:
io.write(sprintf(string, obj, ...)
or
$stdout.write(sprintf(string, obj, ...)
+ (Integer) putc(int)
Equivalent to:
$stdout.putc(int)
Refer to the documentation for IO#putc for important information regarding multi-byte characters.
+ (nil) puts(obj, ...)
Equivalent to
$stdout.puts(obj, ...)
+ (Object) raise + (Object) raise(string) + (Object) raise(exception[, string [, array]]) + (Object) fail + (Object) fail(string) + (Object) fail(exception[, string [, array]])
With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.
raise "Failed to create socket"
raise ArgumentError, "No parameters", caller
+ (Numeric) rand(max = 0) + (Float) rand + (Numeric) rand(limit)
If max is Range, returns a pseudorandom number where range.member(number) == true.
Or else converts max to an integer using max1 = max.to_i.abs.
Then if max is nil the result is zero, returns a pseudorandom floating point number greater than or equal to 0.0 and less than 1.0.
Otherwise, returns a pseudorandom integer greater than or equal to zero and less than max1.
Kernel::srand may be used to ensure repeatable sequences of random numbers between different runs of the program. Ruby currently uses a modified Mersenne Twister with a period of 2**19937-1.
srand 1234 #=> 0
[ rand, rand ] #=> [0.191519450163469, 0.49766366626136]
[ rand(10), rand(1000) ] #=> [6, 817]
srand 1234 #=> 1234
[ rand, rand ] #=> [0.191519450163469, 0.49766366626136]
+ (Array) readlines(sep = $/) + (Array) readlines(limit) + (Array) readlines(sep, limit)
Returns an array containing the lines returned by calling Kernel.gets(sep) until the end of file.
+ (Boolean) require(name)
Loads the given name, returning true if successful and false if the feature is already loaded.
If the filename does not resolve to an absolute path, it will be searched for in the directories listed in $LOAD_PATH ($:).
If the filename has the extension ".rb", it is loaded as a source file; if the extension is ".so", ".o", or ".dll", or the default shared library extension on the current platform, Ruby loads the shared library as a Ruby extension. Otherwise, Ruby tries adding ".rb", ".so", and so on to the name until found. If the file named cannot be found, a LoadError will be raised.
For Ruby extensions the filename given may use any shared library extension. For example, on Linux the socket extension is "socket.so" and require 'socket.dll' will load the socket extension.
The absolute path of the loaded file is added to $LOADED_FEATURES ($"). A file will not be loaded again if its path already appears in $". For example, require 'a'; require './a' will not load a.rb again.
require "my-library.rb"
require "db-driver"
+ (Boolean) resolveClassMethod(name)
Dynamically provides an implementation for a given selector for a class method. This method allows you to dynamically provide an implementation for a given selector. See resolveInstanceMethod: for further discussion.
+ (Boolean) resolveInstanceMethod(name)
Dynamically provides an implementation for a given selector for an instance method. This method and resolveClassMethod: allow you to dynamically provide an implementation for a given selector.An Objective-C method is simply a C function that take at least two arguments—self and _cmd. Using the class_addMethod function, you can add a function to a class as a method. Given the following function:you can use resolveInstanceMethod: to dynamically add it to a class as a method (called resolveThisMethodDynamically) like this:
+ (Object) setVersion(aVersion)
Sets the receiver's version number. The version number is helpful when instances of the class are to be archived and reused later. The default version is 0.
+ (String) format(format_string[, arguments...]) + (String) sprintf(format_string[, arguments...])
Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result.
The syntax of a format sequence is follows.
%[flags][width][.precision]type
A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation.
The field type characters are:
Field | Integer Format
------+--------------------------------------------------------------
b | Convert argument as a binary number.
| Negative numbers will be displayed as a two's complement
| prefixed with `..1'.
B | Equivalent to `b', but uses an uppercase 0B for prefix
| in the alternative format by #.
d | Convert argument as a decimal number.
i | Identical to `d'.
o | Convert argument as an octal number.
| Negative numbers will be displayed as a two's complement
| prefixed with `..7'.
u | Identical to `d'.
x | Convert argument as a hexadecimal number.
| Negative numbers will be displayed as a two's complement
| prefixed with `..f' (representing an infinite string of
| leading 'ff's).
X | Equivalent to `x', but uses uppercase letters.
Field | Float Format
------+--------------------------------------------------------------
e | Convert floating point argument into exponential notation
| with one digit before the decimal point as [-]d.dddddde[+-]dd.
| The precision specifies the number of digits after the decimal
| point (defaulting to six).
E | Equivalent to `e', but uses an uppercase E to indicate
| the exponent.
f | Convert floating point argument as [-]ddd.dddddd,
| where the precision specifies the number of digits after
| the decimal point.
g | Convert a floating point number using exponential form
| if the exponent is less than -4 or greater than or
| equal to the precision, or in dd.dddd form otherwise.
| The precision specifies the number of significant digits.
G | Equivalent to `g', but use an uppercase `E' in exponent form.
a | Convert floating point argument as [-]0xh.hhhhp[+-]dd,
| which is consisted from optional sign, "0x", fraction part
| as hexadecimal, "p", and exponential part as decimal.
A | Equivalent to `a', but use uppercase `X' and `P'.
Field | Other Format
------+--------------------------------------------------------------
c | Argument is the numeric code for a single character or
| a single character string itself.
p | The valuing of argument.inspect.
s | Argument is a string to be substituted. If the format
| sequence contains a precision, at most that many characters
| will be copied.
% | A percent sign itself will be displayed. No argument taken.
The flags modifies the behavior of the formats. The flag characters are:
Flag | Applies to | Meaning
---------+---------------+-----------------------------------------
space | bBdiouxX | Leave a space at the start of
| aAeEfgG | non-negative numbers.
| (numeric fmt) | For `o', `x', `X', `b' and `B', use
| | a minus sign with absolute value for
| | negative values.
---------+---------------+-----------------------------------------
(digit)$ | all | Specifies the absolute argument number
| | for this field. Absolute and relative
| | argument numbers cannot be mixed in a
| | sprintf string.
---------+---------------+-----------------------------------------
# | bBoxX | Use an alternative format.
| aAeEfgG | For the conversions `o', increase the precision
| | until the first digit will be `0' if
| | it is not formatted as complements.
| | For the conversions `x', `X', `b' and `B'
| | on non-zero, prefix the result with ``0x'',
| | ``0X'', ``0b'' and ``0B'', respectively.
| | For `a', `A', `e', `E', `f', `g', and 'G',
| | force a decimal point to be added,
| | even if no digits follow.
| | For `g' and 'G', do not remove trailing zeros.
---------+---------------+-----------------------------------------
+ | bBdiouxX | Add a leading plus sign to non-negative
| aAeEfgG | numbers.
| (numeric fmt) | For `o', `x', `X', `b' and `B', use
| | a minus sign with absolute value for
| | negative values.
---------+---------------+-----------------------------------------
- | all | Left-justify the result of this conversion.
---------+---------------+-----------------------------------------
0 (zero) | bBdiouxX | Pad with zeros, not spaces.
| aAeEfgG | For `o', `x', `X', `b' and `B', radix-1
| (numeric fmt) | is used for negative numbers formatted as
| | complements.
---------+---------------+-----------------------------------------
* | all | Use the next argument as the field width.
| | If negative, left-justify the result. If the
| | asterisk is followed by a number and a dollar
| | sign, use the indicated argument as the width.
Examples of flags:
# `+' and space flag specifies the sign of non-negative numbers.
sprintf("%d", 123) #=> "123"
sprintf("%+d", 123) #=> "+123"
sprintf("% d", 123) #=> " 123"
# `#' flag for `o' increases number of digits to show `0'.
# `+' and space flag changes format of negative numbers.
sprintf("%o", 123) #=> "173"
sprintf("%#o", 123) #=> "0173"
sprintf("%+o", -123) #=> "-173"
sprintf("%o", -123) #=> "..7605"
sprintf("%#o", -123) #=> "..7605"
# `#' flag for `x' add a prefix `0x' for non-zero numbers.
# `+' and space flag disables complements for negative numbers.
sprintf("%x", 123) #=> "7b"
sprintf("%#x", 123) #=> "0x7b"
sprintf("%+x", -123) #=> "-7b"
sprintf("%x", -123) #=> "..f85"
sprintf("%#x", -123) #=> "0x..f85"
sprintf("%#x", 0) #=> "0"
# `#' for `X' uses the prefix `0X'.
sprintf("%X", 123) #=> "7B"
sprintf("%#X", 123) #=> "0X7B"
# `#' flag for `b' add a prefix `0b' for non-zero numbers.
# `+' and space flag disables complements for negative numbers.
sprintf("%b", 123) #=> "1111011"
sprintf("%#b", 123) #=> "0b1111011"
sprintf("%+b", -123) #=> "-1111011"
sprintf("%b", -123) #=> "..10000101"
sprintf("%#b", -123) #=> "0b..10000101"
sprintf("%#b", 0) #=> "0"
# `#' for `B' uses the prefix `0B'.
sprintf("%B", 123) #=> "1111011"
sprintf("%#B", 123) #=> "0B1111011"
# `#' for `e' forces to show the decimal point.
sprintf("%.0e", 1) #=> "1e+00"
sprintf("%#.0e", 1) #=> "1.e+00"
# `#' for `f' forces to show the decimal point.
sprintf("%.0f", 1234) #=> "1234"
sprintf("%#.0f", 1234) #=> "1234."
# `#' for `g' forces to show the decimal point.
# It also disables stripping lowest zeros.
sprintf("%g", 123.4) #=> "123.4"
sprintf("%#g", 123.4) #=> "123.400"
sprintf("%g", 123456) #=> "123456"
sprintf("%#g", 123456) #=> "123456."
The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field.
Examples of width:
# padding is done by spaces, width=20
# 0 or radix-1. <------------------>
sprintf("%20d", 123) #=> " 123"
sprintf("%+20d", 123) #=> " +123"
sprintf("%020d", 123) #=> "00000000000000000123"
sprintf("%+020d", 123) #=> "+0000000000000000123"
sprintf("% 020d", 123) #=> " 0000000000000000123"
sprintf("%-20d", 123) #=> "123 "
sprintf("%-+20d", 123) #=> "+123 "
sprintf("%- 20d", 123) #=> " 123 "
sprintf("%020x", -123) #=> "..ffffffffffffffff85"
For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.)
Examples of precisions:
# precision for `d', 'o', 'x' and 'b' is
# minimum number of digits <------>
sprintf("%20.8d", 123) #=> " 00000123"
sprintf("%20.8o", 123) #=> " 00000173"
sprintf("%20.8x", 123) #=> " 0000007b"
sprintf("%20.8b", 123) #=> " 01111011"
sprintf("%20.8d", -123) #=> " -00000123"
sprintf("%20.8o", -123) #=> " ..777605"
sprintf("%20.8x", -123) #=> " ..ffff85"
sprintf("%20.8b", -11) #=> " ..110101"
# "0x" and "0b" for `#x' and `#b' is not counted for
# precision but "0" for `#o' is counted. <------>
sprintf("%#20.8d", 123) #=> " 00000123"
sprintf("%#20.8o", 123) #=> " 00000173"
sprintf("%#20.8x", 123) #=> " 0x0000007b"
sprintf("%#20.8b", 123) #=> " 0b01111011"
sprintf("%#20.8d", -123) #=> " -00000123"
sprintf("%#20.8o", -123) #=> " ..777605"
sprintf("%#20.8x", -123) #=> " 0x..ffff85"
sprintf("%#20.8b", -11) #=> " 0b..110101"
# precision for `e' is number of
# digits after the decimal point <------>
sprintf("%20.8e", 1234.56789) #=> " 1.23456789e+03"
# precision for `f' is number of
# digits after the decimal point <------>
sprintf("%20.8f", 1234.56789) #=> " 1234.56789000"
# precision for `g' is number of
# significant digits <------->
sprintf("%20.8g", 1234.56789) #=> " 1234.5679"
# <------->
sprintf("%20.8g", 123456789) #=> " 1.2345679e+08"
# precision for `s' is
# maximum number of characters <------>
sprintf("%20.8s", "string test") #=> " string t"
Examples:
sprintf("%d %04x", 123, 123) #=> "123 007b"
sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'"
sprintf("%1$*2$s %2$d %1$s", "hello", 8) #=> " hello 8 hello"
sprintf("%1$*2$s %2$d", "hello", -8) #=> "hello -8"
sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> "+1.23: 1.23:1.23"
sprintf("%u", -123) #=> "-123"
For more complex formatting, Ruby supports a reference by name.
%
Exapmles:
sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 })
#=> 1 : 2.000000
sprintf("%{foo}f", { :foo => 1 })
# => "1f"
+ (Object) srand(number = 0)
Seeds the pseudorandom number generator to the value of number. If number is omitted, seeds the generator using a combination of the time, the process id, and a sequence number. (This is also the behavior if Kernel::rand is called without previously calling srand, but without the sequence.) By setting the seed to a known value, scripts can be made deterministic during testing. The previous seed value is returned. Also see Kernel::rand.
+ (Class) superclass
Returns the class object for the receiver’s superclass.
+ (Object) test(int_cmd, file1[, file2])
Uses the integer aCmd to perform various tests on file1 (first table below) or on file1 and file2 (second table).
File tests on a single file:
Test Returns Meaning
"A" | Time | Last access time for file1
"b" | boolean | True if file1 is a block device
"c" | boolean | True if file1 is a character device
"C" | Time | Last change time for file1
"d" | boolean | True if file1 exists and is a directory
"e" | boolean | True if file1 exists
"f" | boolean | True if file1 exists and is a regular file
"g" | boolean | True if file1 has the \CF{setgid} bit
| | set (false under NT)
"G" | boolean | True if file1 exists and has a group
| | ownership equal to the caller's group
"k" | boolean | True if file1 exists and has the sticky bit set
"l" | boolean | True if file1 exists and is a symbolic link
"M" | Time | Last modification time for file1
"o" | boolean | True if file1 exists and is owned by
| | the caller's effective uid
"O" | boolean | True if file1 exists and is owned by
| | the caller's real uid
"p" | boolean | True if file1 exists and is a fifo
"r" | boolean | True if file1 is readable by the effective
| | uid/gid of the caller
"R" | boolean | True if file is readable by the real
| | uid/gid of the caller
"s" | int/nil | If file1 has nonzero size, return the size,
| | otherwise return nil
"S" | boolean | True if file1 exists and is a socket
"u" | boolean | True if file1 has the setuid bit set
"w" | boolean | True if file1 exists and is writable by
| | the effective uid/gid
"W" | boolean | True if file1 exists and is writable by
| | the real uid/gid
"x" | boolean | True if file1 exists and is executable by
| | the effective uid/gid
"X" | boolean | True if file1 exists and is executable by
| | the real uid/gid
"z" | boolean | True if file1 exists and has a zero length
Tests that take two files:
"-" | boolean | True if file1 and file2 are identical
"=" | boolean | True if the modification times of file1
| | and file2 are equal
"<" | boolean | True if the modification time of file1
| | is prior to that of file2
">" | boolean | True if the modification time of file1
| | is after that of file2
+ (Object) throw(tag[, obj])
Transfers control to the end of the active catch block waiting for tag. Raises ArgumentError if there is no catch block for the tag. The optional second parameter supplies a return value for the catch block, which otherwise defaults to nil. For examples, see Kernel::catch.
+ (nil) trace_var(symbol, cmd) + (nil) trace_var(symbol) {|val| ... }
Controls tracing of assignments to global variables. The parameter +symbol_ identifies the variable (as either a string name or a symbol identifier). cmd (which may be a string or a Proc object) or block is executed whenever the variable is assigned. The block or Proc object receives the variable's new value as a parameter. Also see Kernel::untrace_var.
trace_var :$_, proc {|v| puts "$_ is now '#{v}'" }
$_ = "hello"
$_ = ' there'
produces:
$_ is now 'hello'
$_ is now ' there'
+ (Object) trap(signal, command) + (Object) trap(signal) {|| ... }
Specifies the handling of signals. The first parameter is a signal name (a string such as "SIGALRM", "SIGUSR1", and so on) or a signal number. The characters "SIG" may be omitted from the signal name. The command or block specifies code to be run when the signal is raised. If the command is the string "IGNORE" or "SIG_IGN", the signal will be ignored. If the command is "DEFAULT" or "SIG_DFL", the Ruby's default handler will be invoked. If the command is "EXIT", the script will be terminated by the signal. If the command is "SYSTEM_DEFAULT", the operating system's default handler will be invoked. Otherwise, the given command or block will be run. The special signal name "EXIT" or signal number zero will be invoked just prior to program termination. trap returns the previous handler for the given signal.
Signal.trap(0, proc { puts "Terminating: #{$$}" })
Signal.trap("CLD") { puts "Child died" }
fork && Process.wait
produces:
Terminating: 27461
Child died
Terminating: 27460
+ (Array?) untrace_var(symbol[, cmd])
Removes tracing for the specified command on the given global variable and returns nil. If no command is specified, removes all tracing for that variable and returns an array containing the commands actually removed.
+ (Integer) version
Returns the version number assigned to the class. If no version has been set, the default is 0. Version numbers are needed for decoding or unarchiving, so older versions of an object can be detected and decoded correctly.Caution should be taken when obtaining the version from within an NSCoding protocol or other methods. Use the class name explicitly when getting a class version number: Don’t simply send version to the return value of class—a subclass version number may be returned instead.
Instance Method Details
- (Object) !
Boolean negate.
- (Object) !=
Returns true if two objects are not-equal, otherwise false.
- (Object) !~
Returns true if two objects do not match (using the =~ method), otherwise false.
- (0?) <=>(other)
Returns 0 if obj === other, otherwise nil.
- (Boolean) ==(other) - (Boolean) equal?(other) - (Boolean) eql?(other)
Equality---At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant 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
- (Boolean) ===(other)
Case Equality---For class Object, effectively the same as calling #==, but typically overridden by descendants to provide meaningful semantics in case statements.
- (nil) =~(other)
- (Symbol) __method__ - (Symbol) __callee__
Returns the name of the current method as a Symbol. If called outside of a method, it returns nil.
- (Symbol) __method__ - (Symbol) __callee__
Returns the name of the current method as a Symbol. If called outside of a method, it returns nil.
- (Object) send(symbol[, args...]) - (Object) __send__(symbol[, args...])
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"
- (Object) __type__
:nodoc:
- (Object) autoContentAccessingProxy
Creates and returns a proxy for the receiving object This method creates and returns a proxy for the receiving object, if the receiver adopts the NSDiscardableContent protocol and still has undiscarded content.The proxy calls beginContentAccess on the receiver to keep the content available as long as the proxy lives, and calls endContentAccess when the proxy is deallocated.The wrapper object is otherwise a subclass of NSProxy and forwards messages to the original receiver object as an NSProxy does. This method can be used to hide an NSDiscardableContent object's content volatility by creating an object that responds to the same messages but holds the contents of the original receiver available as long as the created proxy lives. Thus hidden, the NSDiscardableContent object (by way of the proxy) can be given out to unsuspecting recipients of the object who would otherwise not know they might have to call beginContentAccess and endContentAccess around particular usages (specific to each NSDiscardableContent object) of the NSDiscardableContent object.
- (Object) awakeAfterUsingCoder(aDecoder)
Overridden by subclasses to substitute another object in place of the object that was decoded and subsequently received this message. You can use this method to eliminate redundant objects created by the coder. For example, if after decoding an object you discover that an equivalent object already exists, you can return the existing object. If a replacement is returned, your overriding method is responsible for releasing the receiver. This method is invoked by NSCoder. NSObject’s implementation simply returns self.
- (Class) classForCoder
- (Class) classForKeyedArchiver
Overridden by subclasses to substitute a new class for instances during keyed archiving. The object will be encoded as if it were a member of the returned class. The results of this method are overridden by the encoder class and instance name to class encoding tables. If nil is returned, the result of this method is ignored.
- (Object) clone
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.
- (Object) copy
Returns the object returned by copyWithZone:. This is a convenience method for classes that adopt the NSCopying protocol. An exception is raised if there is no implementation for copyWithZone:.NSObject does not itself support the NSCopying protocol. Subclasses must support the protocol and implement the copyWithZone: method. A subclass version of the copyWithZone: method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject.
- (Object) dealloc
Deallocates the memory occupied by the receiver. Subsequent messages to the receiver may generate an error indicating that a message was sent to a deallocated object (provided the deallocated memory hasn’t been reused yet).You override this method to dispose of resources other than the object’s instance variables, for example:In an implementation of dealloc, do not invoke the superclass’s implementation. Typically you should try to avoid managing the lifetime of resources such as file descriptors using dealloc.You never send a dealloc message directly. Instead, an object’s dealloc method is invoked by the runtime. See Advanced Memory Management Programming Guide for more details.
- (Method) define_singleton_method(symbol, method) - (Proc) define_singleton_method(symbol) { ... }
Defines a singleton method in the receiver. The method parameter can be a Proc, a Method or an UnboundMethod object. If a block is specified, it is used as the method body.
class A
class << self
def class_name
to_s
end
end
end
A.define_singleton_method(:who_am_i) do
"I am: #{class_name}"
end
A.who_am_i # ==> "I am: A"
guy = "Bob"
guy.define_singleton_method(:hello) { "#{self}: Hello there!" }
guy.hello #=> "Bob: Hello there!"
- (Object) doesNotRecognizeSelector(aSelector)
Handles messages the receiver doesn’t recognize. The runtime system invokes this method whenever an object receives an aSelector message it can’t respond to or forward. This method, in turn, raises an NSInvalidArgumentException, and generates an error message. Any doesNotRecognizeSelector: messages are generally sent only by the runtime system. However, they can be used in program code to prevent a method from being inherited. For example, an NSObject subclass might renounce the copy or init method by re-implementing it to include a doesNotRecognizeSelector: message as follows:The _cmd variable is a hidden argument passed to every method that is the current selector; in this example, it identifies the selector for the copy method. This code prevents instances of the subclass from responding to copy messages or superclasses from forwarding copy messages—although respondsToSelector: will still report that the receiver has access to a copy method.If you override this method, you must call super or raise an NSInvalidArgumentException exception at the end of your implementation. In other words, this method must not return normally; it must always result in an exception being thrown.
- (Object) dup
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 descendant classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendant 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.
- (Object) to_enum(method = :each, *args) - (Object) enum_for(method = :each, *args)
Creates a new Enumerator which will enumerate by on calling method on obj.
method |
the method to call on obj to generate the enumeration |
args |
arguments that will be passed in method in addition to the item itself. Note that the number of args must not exceed the number expected by method |
Example
str = "xyz"
enum = str.enum_for(:each_byte)
enum.each { |b| puts b }
# => 120
# => 121
# => 122
# protect an array from being modified by some_method
a = [1, 2, 3]
some_method(a.to_enum)
- (Boolean) ==(other) - (Boolean) equal?(other) - (Boolean) eql?(other)
Equality---At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant 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
- (Boolean) ==(other) - (Boolean) equal?(other) - (Boolean) eql?(other)
Equality---At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant 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
- (Object) extend
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"
- (Object) finalize
The garbage collector invokes this method on the receiver before disposing of the memory it uses. (Deprecated. Garbage collection is deprecated in OS X v10.8; instead,you should use AutomaticReference Counting—see Transitioning to ARC Release Notes.) The garbage collector invokes this method on the receiver before disposing of the memory it uses. When garbage collection is enabled, this method is invoked instead of dealloc.You can override this method to relinquish resources the receiver has obtained, as shown in the following example:Typically, however, you are encouraged to relinquish resources prior to finalization if at all possible. For more details, see “Implementing a finalize Method”.
- (Object) forwardingTargetForSelector(aSelector)
Returns the object to which unrecognized messages should first be directed. If an object implements (or inherits) this method, and returns a non-nil (and non-self) result, that returned object is used as the new receiver object and the message dispatch resumes to that new object. (Obviously if you return self from this method, the code would just fall into an infinite loop.)If you implement this method in a non-root class, if your class has nothing to return for the given selector then you should return the result of invoking super’s implementation. This method gives an object a chance to redirect an unknown message sent to it before the much more expensive forwardInvocation: machinery takes over. This is useful in basic proxying situations and can be an order of magnitude faster than regular forwarding. It is not useful where the goal of the forwarding is to capture the NSInvocation, or manipulate the arguments or return value during the forwarding.
- (Object) forwardInvocation(anInvocation)
Overridden by subclasses to forward messages to other objects. When an object is sent a message for which it has no corresponding method, the runtime system gives the receiver an opportunity to delegate the message to another receiver. It delegates the message by creating an NSInvocation object representing the message and sending the receiver a forwardInvocation: message containing this NSInvocation object as the argument. The receiver’s forwardInvocation: method can then choose to forward the message to another object. (If that object can’t respond to the message either, it too will be given a chance to forward it.)The forwardInvocation: message thus allows an object to establish relationships with other objects that will, for certain messages, act on its behalf. The forwarding object is, in a sense, able to “inherit” some of the characteristics of the object it forwards the message to.Important: To respond to methods that your object does not itself recognize, you must override methodSignatureForSelector: in addition to forwardInvocation:. The mechanism for forwarding messages uses information obtained from methodSignatureForSelector: to create the NSInvocation object to be forwarded. Your overriding method must provide an appropriate method signature for the given selector, either by preformulating one or by asking another object for one.An implementation of the forwardInvocation: method has two tasks:To locate an object that can respond to the message encoded in anInvocation. This object need not be the same for all messages. To send the message to that object using anInvocation. anInvocation will hold the result, and the runtime system will extract and deliver this result to the original sender.In the simple case, in which an object forwards messages to just one destination (such as the hypothetical friend instance variable in the example below), a forwardInvocation: method could be as simple as this:The message that’s forwarded must have a fixed number of arguments; variable numbers of arguments (in the style of printf()) are not supported.The return value of the forwarded message is returned to the original sender. All types of return values can be delivered to the sender: id types, structures, double-precision floating-point numbers. Implementations of the forwardInvocation: method can do more than just forward messages. forwardInvocation: can, for example, be used to consolidate code that responds to a variety of different messages, thus avoiding the necessity of having to write a separate method for each selector. A forwardInvocation: method might also involve several other objects in the response to a given message, rather than forward it to just one.NSObject’s implementation of forwardInvocation: simply invokes the doesNotRecognizeSelector: method; it doesn’t forward any messages. Thus, if you choose not to implement forwardInvocation:, sending unrecognized messages to objects will raise exceptions.
- (Object) freeze
Prevents further modifications to obj. A RuntimeError will be raised if modification is attempted. There is no way to unfreeze a frozen object. See also Object#frozen?.
This method returns self.
a = [ "a", "b", "c" ]
a.freeze
a << "z"
produces:
prog.rb:3:in `<<': can't modify frozen array (RuntimeError)
from prog.rb:3
- (Boolean) frozen?
Returns the freeze status of obj.
a = [ "a", "b", "c" ]
a.freeze #=> ["a", "b", "c"]
a.frozen? #=> true
- (Object) init
Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated. An init message is coupled with an alloc (or allocWithZone:) message in the same line of code:An object isn’t ready to be used until it has been initialized. The init method defined in the NSObject class does no initialization; it simply returns self.In a custom implementation of this method, you must invoke super’s designated initializer then initialize and return the new object. If the new object can’t be initialized, the method should return nil.In some cases, an init method might return a substitute object. You must therefore always use the object returned by init, and not the one returned by alloc or allocWithZone:, in subsequent code.
- (Object) initialize_clone
:nodoc:
- (Object) initialize_copy
:nodoc:
- (Object) initialize_dup
:nodoc:
- (String) inspect
Returns a string containing a human-readable representation of obj. If not overridden and no instance variables, uses the to_s method to generate the string. 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 #=> "2008-03-08 19:43:39 +0900"
- (Object) instance_eval(string[, filename [, lineno]]) - (Object) instance_eval {|| ... }
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 KlassWithSecret
def initialize
@secret = 99
end
end
k = KlassWithSecret.new
k.instance_eval { @secret } #=> 99
- (Object) instance_exec(arg...) {|var...| ... }
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
- (Boolean) instance_of?
Returns true if obj is an instance of the given class. See also Object#kind_of?.
class A; 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
- (Boolean) instance_variable_defined?(symbol)
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
- (Object) instance_variable_get(symbol)
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
- (Object) instance_variable_set(symbol, obj)
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\">"
- (Array) instance_variables
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]
- (Boolean) is_a? - (Boolean) kind_of?
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.is_a? A #=> true
b.is_a? B #=> true
b.is_a? C #=> false
b.is_a? M #=> true
b.kind_of? A #=> true
b.kind_of? B #=> true
b.kind_of? C #=> false
b.kind_of? M #=> true
- (Boolean) is_a? - (Boolean) kind_of?
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.is_a? A #=> true
b.is_a? B #=> true
b.is_a? C #=> false
b.is_a? M #=> true
b.kind_of? A #=> true
b.kind_of? B #=> true
b.kind_of? C #=> false
b.kind_of? M #=> true
- (Object) method(sym)
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"
- (IMP) methodForSelector(aSelector)
Locates and returns the address of the receiver’s implementation of a method so it can be called as a function. If the receiver is an instance, aSelector should refer to an instance method; if the receiver is a class, it should refer to a class method.
- (Array) methods
Returns a list of the names of public and protected methods of obj. This will include all the methods accessible in obj's ancestors.
class Klass
def klass_method()
end
end
k = Klass.new
k.methods[0..9] #=> [:klass_method, :nil?, :===,
# :==~, :!, :eql?
# :hash, :<=>, :class, :singleton_class]
k.methods.length #=> 57
- (NSMethodSignature) methodSignatureForSelector(aSelector)
Returns an NSMethodSignature object that contains a description of the method identified by a given selector. This method is used in the implementation of protocols. This method is also used in situations where an NSInvocation object must be created, such as during message forwarding. If your object maintains a delegate or is capable of handling messages that it does not directly implement, you should override this method to return an appropriate method signature.
- (Object) mutableCopy
Returns the object returned by mutableCopyWithZone: where the zone is nil. This is a convenience method for classes that adopt the NSMutableCopying protocol. An exception is raised if there is no implementation for mutableCopyWithZone:.
- (Boolean) nil?
call_seq:
nil.nil? -> true
<anything_else>.nil? -> false
Only the object nil responds true to nil?.
- (Object) performSelector(aSelector, onThread:thr, withObject:arg, waitUntilDone:wait)
Invokes a method of the receiver on the specified thread using the default mode. You can use this method to deliver messages to other threads in your application. The message in this case is a method of the current object that you want to execute on the target thread. This method queues the message on the run loop of the target thread using the default run loop modes—that is, the modes associated with the NSRunLoopCommonModes constant. As part of its normal run loop processing, the target thread dequeues the message (assuming it is running in one of the default run loop modes) and invokes the desired method.You cannot cancel messages queued using this method. If you want the option of canceling a message on the current thread, you must use either the performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method.
- (Object) performSelector(aSelector, onThread:thr, withObject:arg, waitUntilDone:wait, modes:array)
Invokes a method of the receiver on the specified thread using the specified modes. You can use this method to deliver messages to other threads in your application. The message in this case is a method of the current object that you want to execute on the target thread. This method queues the message on the run loop of the target thread using the run loop modes specified in the array parameter. As part of its normal run loop processing, the target thread dequeues the message (assuming it is running in one of the specified modes) and invokes the desired method. You cannot cancel messages queued using this method. If you want the option of canceling a message on the current thread, you must use either the performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method instead.
- (Object) performSelector(aSelector, withObject:anArgument, afterDelay:delay)
Invokes a method of the receiver on the current thread using the default mode after a delay. This method sets up a timer to perform the aSelector message on the current thread’s run loop. The timer is configured to run in the default mode (NSDefaultRunLoopMode). When the timer fires, the thread attempts to dequeue the message from the run loop and perform the selector. It succeeds if the run loop is running and in the default mode; otherwise, the timer waits until the run loop is in the default mode. If you want the message to be dequeued when the run loop is in a mode other than the default mode, use the performSelector:withObject:afterDelay:inModes: method instead. If you are not sure whether the current thread is the main thread, you can use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method to guarantee that your selector executes on the main thread. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.
- (Object) performSelector(aSelector, withObject:anArgument, afterDelay:delay, inModes:modes)
Invokes a method of the receiver on the current thread using the specified modes after a delay. This method sets up a timer to perform the aSelector message on the current thread’s run loop. The timer is configured to run in the modes specified by the modes parameter. When the timer fires, the thread attempts to dequeue the message from the run loop and perform the selector. It succeeds if the run loop is running and in one of the specified modes; otherwise, the timer waits until the run loop is in one of those modes. If you want the message to be dequeued when the run loop is in a mode other than the default mode, use the performSelector:withObject:afterDelay:inModes: method instead. If you are not sure whether the current thread is the main thread, you can use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method to guarantee that your selector executes on the main thread. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.
- (Object) performSelectorInBackground(aSelector, withObject:arg)
Invokes a method of the receiver on a new background thread. This method creates a new thread in your application, putting your application into multithreaded mode if it was not already. The method represented by aSelector must set up the thread environment just as you would for any other new thread in your program. For more information about how to configure and run threads, see Threading Programming Guide.
- (Object) performSelectorOnMainThread(aSelector, withObject:arg, waitUntilDone:wait)
Invokes a method of the receiver on the main thread using the default mode. You can use this method to deliver messages to the main thread of your application. The main thread encompasses the application’s main run loop, and is where the NSApplication object receives events. The message in this case is a method of the current object that you want to execute on the thread. This method queues the message on the run loop of the main thread using the common run loop modes—that is, the modes associated with the NSRunLoopCommonModes constant. As part of its normal run loop processing, the main thread dequeues the message (assuming it is running in one of the common run loop modes) and invokes the desired method. Multiple calls to this method from the same thread cause the corresponding selectors to be queued and performed in the same same order in which the calls were made.You cannot cancel messages queued using this method. If you want the option of canceling a message on the current thread, you must use either the performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method.
- (Object) performSelectorOnMainThread(aSelector, withObject:arg, waitUntilDone:wait, modes:array)
Invokes a method of the receiver on the main thread using the specified modes. You can use this method to deliver messages to the main thread of your application. The main thread encompasses the application’s main run loop, and is where the NSApplication object receives events. The message in this case is a method of the current object that you want to execute on the thread. This method queues the message on the run loop of the main thread using the run loop modes specified in the array parameter. As part of its normal run loop processing, the main thread dequeues the message (assuming it is running in one of the specified modes) and invokes the desired method. Multiple calls to this method from the same thread cause the corresponding selectors to be queued and performed in the same same order in which the calls were made, assuming the associated run loop modes for each selector are the same. If you specify different modes for each selector, any selectors whose associated mode does not match the current run loop mode are skipped until the run loop subsequently executes in that mode.You cannot cancel messages queued using this method. If you want the option of canceling a message on the current thread, you must use either the performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method.
- (Array) private_methods(all = true)
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.
- (Array) protected_methods(all = true)
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.
- (Object) public_method(sym)
Similar to method, searches public method only.
- (Array) public_methods(all = true)
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.
- (Object) public_send(symbol[, args...])
Invokes the method identified by symbol, passing it any arguments specified. Unlike send, public_send calls public methods only.
1.public_send(:puts, "hello") # causes NoMethodError
- (Numeric) Rational(x[, y])
Returns x/y;
- (Object) replacementObjectForCoder(aCoder)
- (Object) replacementObjectForKeyedArchiver(archiver)
Overridden by subclasses to substitute another object for itself during keyed archiving. This method is called only if no replacement mapping for the object has been set up in the encoder (for example, due to a previous call of replacementObjectForKeyedArchiver: to that object).
- (Boolean) respond_to?(symbol, include_private = false)
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.
If the method is not implemented, as Process.fork on Windows, File.lchmod on GNU/Linux, etc., false is returned.
If the method is not defined, respond_to_missing? method is called and the result is returned.
- (Boolean) respond_to_missing?(symbol, include_private)
Hook method to return whether the obj can respond to id method or not.
See #respond_to?.
- (Object) send(symbol[, args...]) - (Object) __send__(symbol[, args...])
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"
- (Array) singleton_methods(all = true)
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. Only public and protected singleton methods are returned.
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]
- (Object) taint
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.
- (Boolean) tainted?
Returns true if the object is tainted.
- (Object) tap {|x| ... }
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}"}
- (String) to_plist
Returns a string of plist format which is converted from Object.
"foo".to_plist #=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<string>foo</string>\n</plist>\n"
{"foo" => 42}.to_plist #=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>foo</key>\n\t<integer>42</integer>\n</dict>\n</plist>\n"
["foo", "bar"].to_plist #=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<array>\n\t<string>foo</string>\n\t<string>bar</string>\n</array>\n</plist>\n"
- (String) to_s
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."
- (Object) trust
Removes the untrusted mark from obj.
- (Object) untaint
Removes the taint from obj.
- (Object) untrust
Marks obj as untrusted.
- (Boolean) untrusted?
Returns true if the object is untrusted.