Class: String

Inherits:
Object show all
Defined in:
lib/y_support/core_ext/string/misc.rb

Instance Method Summary collapse

Instance Method Details

#default!(default_string) ⇒ Object

If the string is empty, it gets replace with the string given as argument.



49
50
51
# File 'lib/y_support/core_ext/string/misc.rb', line 49

def default! default_string
  strip.empty? ? clear << default_string.to_s : self
end

#standardizeObject

Converts a string into a standard symbol. While Symbol class objects can be created from any string, it is good practice to keep symbols free of whitespaces and weird characters, so that the are typed easily, usable as variable names etc. This method thus removes punctuation, removes superfluous spaces, and underscores the remaining ones, before returning the string.



66
67
68
69
70
71
72
# File 'lib/y_support/core_ext/string/misc.rb', line 66

def standardize
  ς = self.dup
  ",.;".each_char { |c| ς.gsub! c, " " }
  ς.stripn
    .squeeze(" ")
    .underscore_spaces
end

#stripnObject

Like #strip, but also strips newlines.



30
31
32
33
34
# File 'lib/y_support/core_ext/string/misc.rb', line 30

def stripn
  encode( universal_newline: true )
    .gsub("\n", "")
    .strip
end

#to_FloatObject

Float() style conversion, or false if conversion impossible.



19
20
21
22
23
24
25
26
# File 'lib/y_support/core_ext/string/misc.rb', line 19

def to_Float
  begin
    fl = Float stripn
    return fl
  rescue ArgumentError
    return false
  end
end

#to_IntegerObject

Integer() style conversion, or false if conversion impossible.



8
9
10
11
12
13
14
15
# File 'lib/y_support/core_ext/string/misc.rb', line 8

def to_Integer
  begin
    int = Integer stripn
    return int
  rescue ArgumentError
    return false
  end
end

#to_standardized_symObject

Applies #standardize to the receiver and converts the result to a symbol.



76
77
78
79
# File 'lib/y_support/core_ext/string/misc.rb', line 76

def to_standardized_sym
  standardize
    .to_sym
end

#underscore_spacesObject

As it says – replaces spaces with underscores.



55
56
57
# File 'lib/y_support/core_ext/string/misc.rb', line 55

def underscore_spaces
  gsub ' ', '_'
end

#wring_heredocObject

Joins a paragraph of possibly indented, newline separated lines into a single contiguous string.



39
40
41
42
43
44
45
# File 'lib/y_support/core_ext/string/misc.rb', line 39

def wring_heredoc
  encode(universal_newline: true)
    .split("\n")                   # split into lines
    .map( &:strip )                # strip them
    .delete_if( &:blank? )         # delete blank lines
    .join " "                      # and join with whitspace
end