Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/tsplab.rb,
lib/bitlab.rb,
lib/elizalab.rb,
lib/rubylabs.rb

Overview

RubyLabs

Instance Method Summary collapse

Instance Method Details

#code(*args) ⇒ Object

String

In Ruby 1.9 and above elements in strings are chars, not integers. This method adds a code method to the String class that returns a Code object for a single-letter string.



1055
1056
1057
1058
1059
1060
1061
# File 'lib/bitlab.rb', line 1055

def code(*args)
  if self.length > 1
    raise "code: defined only for single characters or integers"
  else
    return self[0].ord.code(*args)
  end
end

#each_permutationObject



1323
1324
1325
1326
1327
1328
1329
# File 'lib/tsplab.rb', line 1323

def each_permutation
  if block_given?
    self.chars.each_permutation { |p| yield p.join('') }
  else
    return self.chars.each_permutation.map { |p| p.join('') }
  end
end

#iordObject

If a character is a letter from the Roman alphabet (upper or lower case, in the range ‘A’ to ‘Z’) map it to a number between 0 and 25, otherwise just return the ASCII code of the letter.

Example:

>> "Ducks!".each_char { |x| puts x.iord }
3
20
2
10
18
33


1535
1536
1537
1538
1539
1540
1541
1542
1543
# File 'lib/rubylabs.rb', line 1535

def iord
  if self[0] >= ?a && self[0] <= ?z
    self[0].ord - ?a.ord
  elsif self[0] >= ?A && self[0] <= ?Z
    self[0].ord - ?A.ord
  else
    self[0].ord
  end
end

#unquoteObject

Call s.unquote to return a copy of string s with double quotes removed from the beginning and end.

Example:

>> s = '"Is it raining?"'
=> "\"Is it raining?\""
>> s.unquote
=> "Is it raining?"


794
795
796
797
798
799
800
# File 'lib/elizalab.rb', line 794

def unquote
  if self[0] == ?" && self[-1] == ?"
    return self.slice(1..-2)
  else
    return self
  end
end