Mundo Maker
¡Bienvenid@ a Mundo Maker!

¿Quieres aprender todo sobre el RPG Maker?



Regístrate y forma parte de Mundo Maker.

[XP] Colección de Snippets para RPG maker

Ver el tema anterior Ver el tema siguiente Ir abajo

RPG Maker XP [XP] Colección de Snippets para RPG maker

Mensaje por Wecoc el 2018-01-12, 18:43

Los Snippets pertenecen a esa clase de scripts a los comúnmente llamo "herramientas de scripter", ya que son códigos que facilitan la creación de otros scripts, y en algunos casos incluso engines. Normalmente son reescrituras o ampliaciones de clases internas (Array, Bitmap, Window...) y suelen ser compatibles con todo. Son especialmente interesantes porque aumentan la potencialidad del programa (y del RGSS).

He creado éste topic para recopilar algunos en el foro, aunque ya subí algunos anteriormente hechos por mí como el Array + y también hay otros muy conocidos como el SDK o el MACL. Podéis encontrar varios en la recopilación de scripts, en el apartado Scripts Especiales.

Dentro del WecTools también se puede encontrar alguno que creé especialmente para ese sistema, pero que podéis usar aunque sea a modo de referencia.
Me centraré en RPG maker XP aunque este tipo de scripts suelen ser compatibles con VX y Ace.

Antes pongo aquí algunos links de interés con algunos de esos Snippets:
HBGames - Scripter's corner : Snippets, Classes, Tips and more
Contenido:
- CircularList (similar a Array), ver module List más abajo (e)
- Window Base con nuevo parámetro sliding (deslizar ventanas) (khmp)
- Linked_List (similar a CircularList, creado para MACL) (Zeriab)
- Atajos de Module para definir accessors y readers (Zeriab)
- Math_Vector3 + Sprite_Float/Sprite_Chunk (crear vectores 3D) (khmp)
- Reset class (desactiva la tecla F12) (Zeriab)
- Multidimensional Array and Hash (hanmac)
- Atajo Object class_defined? (Dargor)
- Array rotate! method (trebor777)
- Table con opción print (Zeriab)

- Mensaje de error con Backtrace, varios (Zeriab & rey meustrus)
- Obtener el ángulo dadas dos coordenadas (BwdYeti)
- Recolorear bitmap, varios posts (BwdYeti)
- Convertir string a otros formatos (BlueScope)
- Obtener y escribir data en archivos INI (rey meustrus)
- GSM - Atajos para obtener los datos de resolución de pantalla (rey meustrus)
- Valor default para Array/Hash mediante Proc (rey meustrus)
- Console Debug Snippets (Cremno & rey meustrus)
- Obtener Width y Height de un PNG fácilmente (Cremno)
- Descargar imagen de internet y guardarla como archivo (Cremno)
- Memorizador de gráficos de Game_Actor (kyonides)

- Atajo para obtener códigos de evento (kyonides)
- Backup Utility (kyonides)
- Reader/Writter para class variables (hanmac, +Yeyinde en 4a pag)
- Controlar Frame Rate (Kain Nobel)
- Quitar comentarios y formato en Scripts.rxdata para ahorrar espacio (Zeriab)
- RPG::MapInfo extendido (rey meustrus)
- Reescritura de Tilemap (rey meustrus)
- Equipment optimizer (SephirothSpawn)
- Obtener nombre de mapa (kyonides)
- Animated message window (SephirothSpawn)
- Table (versión simplificada) (SephirothSpawn)

- Array parser (kyonides)
- Sprite::Transition (SephirothSpawn)
- User32 module (rey meustrus)
- Cambiar viewport de un sprite (rey meustrus)
- API module (SephirothSpawn)
- Table (versión Hash-based) (rey meustrus)
- Comprobador de keys de Hash de Hashes (SephirothSpawn)
- Tirar dados (kyonides)
- Mouse module (varios posts) (SephirothSpawn & Gust)
- Comprobar si cualquier tecla es pulsada (berka)
- Abrir Internet Explorer (berka)
- Convertir Array a Hash (SephirothSpawn)
- Redondear Float a n decimal (berka)
- Game_Switches con opción de rango (kyonides)
- Obtener divisores dentro de un rango (kyonides)
- Bugfix de Terrain Tag para eventos de tile (regi)

- Comprobador de keys de Hash de Hashes (rey meustrus)
- Desactivar Game Pad (Zeriab)
- IDE Scripts (Leer scripts externos fácilmente) (trebor777)
- Redondear Float extendido (BlueScope)
- Z de Eventos personalizado (ForeverZer0)

HBGames - RGSS Table, Color & Tone Classes

Iré subiendo algunos, y quizá también algún pequeño truco.
avatar
Wecoc
Administrador
Administrador



Créditos 12291

Gracias : 646

Volver arriba Ir abajo

RPG Maker XP Re: [XP] Colección de Snippets para RPG maker

Mensaje por Wecoc el 2018-01-13, 01:29

Bueno, como no podía ser de otra forma empiezo con Array, como parte de una colección de scripts independientes a la que llamé rb2RGSS.
En las instrucciones y comentarios del script hay toda la info necesaria para usarlo y cada método tiene un link donde encontraréis su descripción y ejemplos de uso.

Código:
#==============================================================================
# ** [XP] rb2RGSS (Ruby Methods to RGSS) - Array
#------------------------------------------------------------------------------
# PARTE 1. Array                                                  Versión: 1.0
# Autor: Wecoc (libre de uso)                                      13/01/2017
#------------------------------------------------------------------------------
# Ésta colección define algunos métodos que por defecto no están disponibles en
# RPG maker XP pero sí en la versión 2.5 de Ruby.
#------------------------------------------------------------------------------
# Puede obtenerse información y ejemplos de uso en la guía de Ruby:
# https://ruby-doc.org/core-2.5.0/Array.html
#==============================================================================

#==============================================================================
# * Nuevos sinónimos de métodos existentes
#==============================================================================
# append
# initialize_copy
# prepend
# keep_if
#==============================================================================
# * Nuevos métodos
#==============================================================================
# bsearch
# bsearch_index
# count
# cycle
# dig
# drop
# drop_while
# take
# take_while
# sample
# select!
# shuffle
# shuffle!
# sort_by!
# sum
# to_h
#==============================================================================
# * Nuevas funciones a métodos ya existentes
#==============================================================================
# concat    (múltiples argumentos simultáneos)
# index    (llamada con proceso)
# rindex    (llamada con proceso)
# flatten  (con argumento level)
# flatten!  (con argumento level)
# max      (con argumento)
# min      (con argumento)
# pop      (con argumento)
# shift    (con argumento)
# uniq      (llamada con proceso)
# uniq!    (llamada con proceso)
#==============================================================================
# * Especiales
#==============================================================================
# Array.try_convert
#==============================================================================

#==============================================================================
# ** Array
#==============================================================================

class Array
  #--------------------------------------------------------------------------
  # * Array.try_convert(value)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-c-try_convert
  #--------------------------------------------------------------------------
  def Array.try_convert(value)
    return value.to_ary rescue nil
  end
  #--------------------------------------------------------------------------
 
  alias_method(:append,          :push)
  alias_method(:initialize_copy, :replace)
  alias_method(:prepend,        :unshift)
  alias_method(:keep_if,        :select)
 
  #--------------------------------------------------------------------------
  # * bsearch {|x| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-bsearch
  #--------------------------------------------------------------------------
  def bsearch(&block)
    for i in 0...self.size
      value = self[i]
      return value if (yield value) == true
    end
    return nil
  end
  #--------------------------------------------------------------------------
  # * bsearch_index {|x| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-bsearch_index
  #--------------------------------------------------------------------------
  def bsearch_index(&block)
    for i in 0...self.size
      value = self[i]
      return i if (yield value) == true
    end
    return nil
  end
  #--------------------------------------------------------------------------
  # * concat(other_ary1, other_ary2,...)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-concat
  #--------------------------------------------------------------------------
  alias concat_single concat unless $@
  def concat(*args)
    result = []
    for i in 0...args.size
      value = args[i].clone rescue args[i]
      result.push(value)
    end
    for i in 0...result.size
      concat_single(result[i].to_a)
    end
    return self
  end
  #--------------------------------------------------------------------------
  # * count
  # * count(obj)
  # * count { |item| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-concat
  #--------------------------------------------------------------------------
  def count(*args, &block)
    return self.size if args.size == 0 && !block_given?
    result = 0
    for i in 0...self.size
      if block_given?
        result += 1 if yield self[i]
      else
        result += 1 if self[i] == args[0]
      end
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * cycle(n=nil) { |obj| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-cycle
  #--------------------------------------------------------------------------
  def cycle(*args, &block)
    return if !block_given?
    return if args[0].nil? or args[0] <= 0
    count = 0
    loop do
      for i in 0...self.size
        value = self[i]
        yield value
      end
      count += 1
      break if count == args[0]
    end
  end
  #--------------------------------------------------------------------------
  # * dig(idx, ...)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-dig
  #--------------------------------------------------------------------------
  def dig(*args)
    count = 0
    result = self
    loop do
      result = result[args[count]]
      return nil if result.nil?
      count += 1
      break if count == args.size
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * drop(n)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-drop
  #--------------------------------------------------------------------------
  def drop(n)
    self[n...self.size]
  end
  #--------------------------------------------------------------------------
  # * drop_while { |obj| block }
  #--------------------------------------------------------------------------
  # * https://ruby-doc.org/core-2.5.0/Array.html#method-i-drop_while
  #--------------------------------------------------------------------------
  def drop_while(&block)
    return if !block_given?
    n = 0
    for i in 0...self.size
      value = self[i]
      break unless yield value
      n += 1
    end
    return self[n...self.size]
  end
  #--------------------------------------------------------------------------
  # * take(n)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-take
  #--------------------------------------------------------------------------
  def take(n)
    self[0...n]
  end
  #--------------------------------------------------------------------------
  # * take_while { |obj| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-take_while
  #--------------------------------------------------------------------------
  def take_while(&block)
    return if !block_given?
    result = []
    for i in 0...self.size
      value = self[i]
      break unless yield value
      result.push(value)
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * index(obj)
  # * index { |item| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-index
  #--------------------------------------------------------------------------
  alias index_no_block index unless $@
  def index(value=nil, &block)
    return index_no_block(value) if !block_given?
    for i in 0...self.size
      value = self[i]
      return i if yield value
    end
    return nil
  end
  #--------------------------------------------------------------------------
  # * rindex(obj)
  # * rindex { |item| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-rindex
  #--------------------------------------------------------------------------
  alias rindex_no_block rindex unless $@
  def rindex(value=nil, &block)
    return rindex_no_block(value) if !block_given?
    for i in 0...self.size
      i = self.size - i - 1
      value = self[i]
      return i if yield value
    end
    return nil
  end
  #--------------------------------------------------------------------------
  # * flatten
  # * flatten(level)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-flatten
  #--------------------------------------------------------------------------
  alias flatten_no_args flatten unless $@
  def flatten(level=nil)
    return flatten_no_args if level.nil?
    return self if level == 0
    n = 0
    result = self.clone
    loop do
      flat = []
      for i in 0...result.size
        flat.concat(result[i])
      end
      result = flat
      n += 1
      break if n == level
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * flatten!
  # * flatten!(level)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-flatten
  #--------------------------------------------------------------------------
  alias flatten_no_args! flatten! unless $@
  def flatten!(level=nil)
    result = self.flatten(level)
    return nil if self == result
    self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * max
  # * max { |a, b| block }
  # * max(n)
  # * max(n) { |a, b| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-max
  #--------------------------------------------------------------------------
  alias max_no_args max unless $@
  def max(n=nil, &block)
    return max_no_args(&block) if n.nil?
    result = sort(&block).reverse
    return result[0...n]
  end
  #--------------------------------------------------------------------------
  # * min
  # * min { |a, b| block }
  # * min(n)
  # * min(n) { |a, b| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-min
  #--------------------------------------------------------------------------
  alias min_no_args min unless $@
  def min(n=nil, &block)
    return min_no_args(&block) if n.nil?
    result = sort(&block)
    return result[0...n]
  end
  #--------------------------------------------------------------------------
  # * pop
  # * pop(n)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-pop
  #--------------------------------------------------------------------------
  alias pop_no_args pop unless $@
  def pop(n=nil)
    return pop_no_args if n.nil?
    n = self.size - n
    result = self[n...self.size]
    self.replace(self[0...n])
    return result
  end
  #--------------------------------------------------------------------------
  # * shift
  # * shift(n)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-shift
  #--------------------------------------------------------------------------
  alias shift_no_args shift unless $@
  def shift(n=nil)
    return shift_no_args if n.nil?
    result = self[0...n]
    self.replace(self[n...self.size])
    return result
  end
  #--------------------------------------------------------------------------
  # * sample
  # * sample(n)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-sample
  #--------------------------------------------------------------------------
  def sample(value=nil)
    return self[rand(self.size)] if value == nil
    cloned = self.clone
    result = []
    n = 0
    loop do
      index = rand(cloned.size)
      value = cloned[index]
      break if value.nil?
      result.push(value)
      cloned.delete_at(index)
      n += 1
      break if n == value
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * select! {|item| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-select
  #--------------------------------------------------------------------------
  def select!(&block)
    result = self.select(&block)
    return nil if self == result
    self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * shuffle
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-shuffle
  #--------------------------------------------------------------------------
  def shuffle
    cloned = self.clone
    result = []
    while cloned.size > 0
      result.push(cloned.delete_at(rand(cloned.size)))
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * shuffle!
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-shuffle
  #--------------------------------------------------------------------------
  def shuffle!
    self.replace(self.shuffle)
  end
  #--------------------------------------------------------------------------
  # * sort_by! { |obj| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-sort_by
  #--------------------------------------------------------------------------
  def sort_by!(&block)
    result = self.sort_by(&block)
    return nil if self == result
    self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * sum(init=0)
  # * sum(init=0) {|e| expr }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-sum
  #--------------------------------------------------------------------------
  def sum(init=0, &block)
    for i in 0...self.size
      if block_given?
        init += yield(self[i])
      else
        init += self[i]
      end
    end
    return init
  end
  #--------------------------------------------------------------------------
  # * to_h
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-to_h
  #--------------------------------------------------------------------------
  def to_h
    result = Hash.new
    for i in 0...self.size
      result[self[i][0]] = self[i][1]
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * uniq
  # * uniq { |item| ... }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-uniq
  #--------------------------------------------------------------------------
  alias uniq_no_block uniq unless $@
  def uniq(&block)
    return uniq_no_block if !block_given?
    result = []
    for i in 0...self.size
      insert_current = true
      current = self[i]
      for j in 0...result.size
        checked = result[j]
        if (yield current) == (yield checked)
          insert_current = false
          next i
        end
      end
      result.push(current) if insert_current
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * uniq!
  # * uniq! { |item| ... }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Array.html#method-i-uniq
  #--------------------------------------------------------------------------
  def uniq!(&block)
    result = self.uniq(&block)
    return nil if self == result
    self.replace(result)
  end
end

Pronto subiré más, si tenéis algún aporte o bien alguna duda sobre lo aportado hasta ahora, comentad.
Edit: Arreglado bug en los métodos :max y :min


Última edición por Wecoc el 2018-01-13, 19:25, editado 3 veces
avatar
Wecoc
Administrador
Administrador



Créditos 12291

Gracias : 646

Volver arriba Ir abajo

RPG Maker XP Re: [XP] Colección de Snippets para RPG maker

Mensaje por orochii el 2018-01-13, 06:54

Esto es un snippet digamos, para cuando quieres hacer cambios a animaciones, a todos los frames y todos los sprites de muchas animaciones seguidas. En este caso es para mover N animaciones un tanto hacia arriba/abajo/izquierda/derecha. Lo ocupaba para arreglar unas animaciones de batalla y me daba flojera ir de una por una xD.

Código:
def batch_fix_offset_anims(startAnim,endAnim, offX, offY)
  $data_animations = load_data("Data/Animations.rxdata")
  (startAnim..endAnim).each { |animation|
    $data_animations[animation].frames.each { |frame|
      # Move thing x/y by specific offset.
      (0..15).each {|i|
        pattern = frame.cell_data[i,0]
        if(pattern != nil || pattern > -1)
          frame.cell_data[i,1] += offX;
          frame.cell_data[i,2] += offY;
        end
      }
    }
  }
  save_data($data_animations,"Data/Animations.rxdata")
end

Me gustaría tomar un tiempo y expandir mi editor de animaciones con estas cosas xd. Pero :V.
avatar
orochii
Reportero

0/3

Créditos 7794

Gracias : 462

Volver arriba Ir abajo

RPG Maker XP Re: [XP] Colección de Snippets para RPG maker

Mensaje por Wecoc el 2018-01-14, 00:26

Gracias orochii, está bastante bien :)
Subo dos más, Enumerable y Numeric. Por ahora todos estos scripts son independientes entre ellos, e incluso entre métodos sueltos excepto algún caso que ya indiqué en los comentarios.

Código:
#==============================================================================
# ** [XP] rb2RGSS (Ruby Methods to RGSS) - Enumerable
#------------------------------------------------------------------------------
# PARTE 2. Enumerable                                            Versión: 1.0
# Autor: Wecoc (libre de uso)                                      13/01/2017
#------------------------------------------------------------------------------
# Ésta colección define algunos métodos que por defecto no están disponibles en
# RPG maker XP pero sí en la versión 2.5 de Ruby.
#------------------------------------------------------------------------------
# Puede obtenerse información y ejemplos de uso en la guía de Ruby:
# https://ruby-doc.org/core-2.5.0/Enumerable.html
#==============================================================================

#==============================================================================
# * Nuevos métodos
#==============================================================================
# chunk
# flat_map
# each_cons
# each_slice
# each_with_object
# find_index
# grep_v
# group_by
# max_by
# min_by
# minmax
# minmax_by
# none?
# one?
# some?
# reverse_each
# bsearch
# bsearch_index
# cover?
# size
#==============================================================================
# * Nuevas funciones a métodos ya existentes
#==============================================================================
# all?      (con argumento)
# any?      (con argumento)
# include?  (basado en Array)
# first    (con argumento)
# last      (con argumento)
#==============================================================================

#==============================================================================
# ** Enumerable
#==============================================================================

module Enumerable
  #--------------------------------------------------------------------------
  # * all?(pattern)
  # * all? { |obj| block }
  # * all?(pattern) { |obj| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-all-3F
  #--------------------------------------------------------------------------
  alias all_no_value all? unless $@
  def all?(value=nil, &block)
    return all_no_value(&block) if value.nil?
    array = self.to_a
    for i in 0...array.size
      case value
      when Regexp
        next if array[i].grep(value).size > 0
      else
        next if array[i].is_a?(value)
      end
      return false
    end
    return true
  end
  #--------------------------------------------------------------------------
  # * any?(pattern)
  # * any? { |obj| block }
  # * any?(pattern) { |obj| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-any-3F
  #--------------------------------------------------------------------------
  alias any_no_value any? unless $@
  def any?(value=nil, &block)
    return any_no_value(&block) if value.nil?
    array = self.to_a
    for i in 0...array.size
      case value
      when Regexp
        return true if array[i].grep(value).size > 0
      else
        return true if array[i].is_a?(value)
      end
    end
    return false
  end
  #--------------------------------------------------------------------------
  # * chunk { |elt| ... }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-chunk
  #--------------------------------------------------------------------------
  def chunk(&block)
    return [] if !block_given? or self.size == 0
    array = self.to_a
    value = yield array[0]
    result = []
    result.push [value, [array[0]]]
    return result if array.size == 1
    for i in 1...array.size
      current_value = yield array[i]
      if current_value == value
        result[-1][1].push array[i]
      else
        value = current_value
        result.push [value, [array[i]]]
      end
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * flat_map
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-flat_map
  #--------------------------------------------------------------------------
  def flat_map(&block)
    return self.map(&block).flatten
  end
  #--------------------------------------------------------------------------
  # * each_cons(n) { ... }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-each_cons
  #--------------------------------------------------------------------------
  def each_cons(n, &block)
    array = self.to_a
    for i in 0..(array.size - n)
      values = []
      for j in 0...n
        values.push(array[i+j])
      end
      yield values
    end
    return nil
  end
  #--------------------------------------------------------------------------
  # * each_slice(n) { ... }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-each_slice
  #--------------------------------------------------------------------------
  def each_slice(n, &block)
    array = self.to_a
    m = (array.size.to_f / n).ceil
    for i in 0...m
      values = []
      for j in 0...n
        index = i * n + j
        break j if index >= array.size
        values.push(array[index])
      end
      yield values
    end
    return nil
  end
  #--------------------------------------------------------------------------
  # * each_with_object(obj) { |(*args), memo_obj| ... }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-each_with_object
  #--------------------------------------------------------------------------
  def each_with_object(obj, &block)
    array = self.to_a
    for i in 0...array.size
      yield array[i], obj
    end
    return obj
  end
  #--------------------------------------------------------------------------
  # * find_index(value)
  # * find_index { |obj| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-find_index
  #--------------------------------------------------------------------------
  def find_index(value=nil, &block)
    array = self.to_a
    return array.index(value) if !block_given?
    for i in 0...array.size
      result = yield array[i]
      return i if result == true
    end
    return nil
  end
  #--------------------------------------------------------------------------
  # * grep_v(pattern)
  # * grep_v(pattern) { |obj| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-grep_v
  #--------------------------------------------------------------------------
  def grep_v(pattern, &block)
    array = self.to_a
    result = []
    for i in 0...array.size
      element = array[i]
      unless self.grep(pattern).include?(element)
        if block_given?
          result.push(yield element)
        else
          result.push(element)
        end
      end
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * group_by { |obj| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-group_by
  #--------------------------------------------------------------------------
  def group_by(&block)
    array = self.to_a
    result = {}
    for i in 0...array.size
      element = array[i]
      current = (yield element)
      if result.keys.include?(current)
        result[current].push(element)
      else
        result[current] = [element]
      end
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * max_by {|obj| block }
  # * max_by(n) {|obj| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-max_by
  #--------------------------------------------------------------------------
  def max_by(n=nil, &block)
    result = self.to_a.sort_by(&block).reverse
    return result[0] if n.nil?
    return result[0...n]
  end
  #--------------------------------------------------------------------------
  # * min_by {|obj| block }
  # * min_by(n) {|obj| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-min_by
  #--------------------------------------------------------------------------
  def min_by(n=nil, &block)
    result = self.to_a.sort_by(&block)
    return result[0] if n.nil?
    return result[0...n]
  end
  #--------------------------------------------------------------------------
  # * minmax
  # * minmax { |a, b| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-minmax
  #--------------------------------------------------------------------------
  def minmax(&block)
    return [min(&block), max(&block)]
  end
  #--------------------------------------------------------------------------
  # * minmin_by {|obj| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-minmax_by
  #--------------------------------------------------------------------------
  # Requiere: Enumerable:max_by
  # Requiere: Enumerable:min_by
  #--------------------------------------------------------------------------
  def minmax_by(&block)
    return [min_by(&block), max_by(&block)]
  end
  #--------------------------------------------------------------------------
  # * none? { |obj| block }
  # * none?(pattern)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-none-3F
  #--------------------------------------------------------------------------
  # Requiere: Enumerable:any? para usarlo con valor asignado
  #--------------------------------------------------------------------------
  def none?(value=nil, &block)
    return any?(&block) == false if value.nil?
    return any?(value, &block) == false
  end
  #--------------------------------------------------------------------------
  # * one? { |obj| block }
  # * one?(pattern)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-one-3F
  #--------------------------------------------------------------------------
  def one?(value=nil, &block)
    return one_no_value(&block) if value.nil?
    array = self.to_a
    result = []
    for i in 0...array.size
      case value
      when Regexp
        result.push(0) if array[i].grep(value).size > 0
      else
        result.push(0) if array[i].is_a?(value)
      end
    end
    return (result.size == 1)
  end
  def one_no_value(&block)
    array = self.to_a
    result = []
    for i in 0...array.size
      if block_given?
        result.push(0) if (yield array[i])
      else
        result.push(0) if !array[i].nil? && !array[i].is_a?(FalseClass)
      end
    end
    return (result.size == 1)
  end
  #--------------------------------------------------------------------------
  # * some? { |obj| block }
  # * some?(pattern)
  #--------------------------------------------------------------------------
  # (Método propio)
  #--------------------------------------------------------------------------
  # Requiere: Enumerable:one?
  # Requiere: Enumerable:any? para usarlo con valor asignado
  #--------------------------------------------------------------------------
  def some?(value=nil, &block)
    return (any?(&block) == true && one?(&block) == false) if value.nil?
    return (any?(value, &block) == true && one?(value, &block) == false)
  end
  #--------------------------------------------------------------------------
  # * reverse_each { |item| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-reverse_each
  #--------------------------------------------------------------------------
  def reverse_each(&block)
    return self.to_a.reverse.each(&block)
  end
end

#==============================================================================
# ** Range
#==============================================================================

class Range
  #--------------------------------------------------------------------------
  # * bsearch {|x| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Range.html#method-i-bsearch
  #--------------------------------------------------------------------------
  # Requiere: Array:bsearch
  #--------------------------------------------------------------------------
  def bsearch(&block)
    return self.to_a.bsearch(&block)
  end
  #--------------------------------------------------------------------------
  # * bsearch_index {|x| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Range.html#method-i-bsearch
  #--------------------------------------------------------------------------
  # Requiere: Array:bsearch_index
  #--------------------------------------------------------------------------
  def bsearch_index(&block)
    return self.to_a.bsearch(&block)
  end
  #--------------------------------------------------------------------------
  # * cover?(obj)
  # * include?(obj)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Range.html#method-i-cover-3F
  # https://ruby-doc.org/core-2.5.0/Range.html#method-i-include-3F
  #--------------------------------------------------------------------------
  alias cover? include? unless $@
  def include?(obj)
    return self.to_a.include?(obj)
  end
  #--------------------------------------------------------------------------
  # * first
  # * first(n)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Range.html#method-i-first
  #--------------------------------------------------------------------------
  alias first_no_value first unless $@
  def first(n=nil)
    return first_no_value if n.nil?
    return self.to_a[0...n]
  end
  #--------------------------------------------------------------------------
  # * last
  # * last(n)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Range.html#method-i-last
  #--------------------------------------------------------------------------
  alias last_no_value last unless $@
  def last(n=nil)
    return last_no_value if n.nil?
    m = self.to_a.size - n
    return self.to_a[m...self.to_a.size]
  end
  #--------------------------------------------------------------------------
  # * size
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Range.html#method-i-size
  #--------------------------------------------------------------------------
  def size
    return self.to_a.size if first.is_a?(Numeric) && last.is_a?(Numeric)
    return nil
  end
end

Código:
#==============================================================================
# ** [XP] rb2RGSS (Ruby Methods to RGSS) - Numeric
#------------------------------------------------------------------------------
# PARTE 3. Numeric                                                Versión: 1.0
# Autor: Wecoc (libre de uso)                                       13/01/2017
#------------------------------------------------------------------------------
# Ésta colección define algunos métodos que por defecto no están disponibles en
# RPG maker XP pero sí en la versión 2.5 de Ruby.
#------------------------------------------------------------------------------
# Puede obtenerse información y ejemplos de uso en la guía de Ruby:
# https://ruby-doc.org/core-2.5.0/Numeric.html
#==============================================================================

#==============================================================================
# * Nuevos métodos (Numeric)
#==============================================================================
# digit
# abs2
# clone
# ord
# even?
# odd?
# pred
# pow
#==============================================================================
# * Nuevos métodos (Integer)
#==============================================================================
# digits
# divisors
# factorize
# gcd
# lcm
# gcdlcm
#==============================================================================
# * Nuevos métodos (Math)
#==============================================================================
# cbrt
# fact
# gamma
# lgamma
# log
# log2
#==============================================================================
# * Nuevas funciones a métodos ya existentes (Numeric)
#==============================================================================
# ceil      (con argumento level)
# floor     (con argumento level)
# truncate  (con argumento level)
# round     (con argumentos level, half)
# Integer   (definir con base distinta de 10)
#==============================================================================
# * Especiales
#==============================================================================
# Integer.sqrt
#==============================================================================

#==============================================================================
# ** Numeric
#==============================================================================

class Numeric
  #--------------------------------------------------------------------------
  # * digit(pos)
  #--------------------------------------------------------------------------
  def digit(n)
    result = (self.abs * (10 ** -n)).floor
    result_next = (self.abs * (10 ** (-n-1))).floor * 10
    return result - result_next
  end
  #--------------------------------------------------------------------------
  # * abs2
  #--------------------------------------------------------------------------
  def abs2()    return self * self      end
  #--------------------------------------------------------------------------
  # * clone
  #--------------------------------------------------------------------------
  def clone()   return self             end
  #--------------------------------------------------------------------------
  # * ord
  #--------------------------------------------------------------------------
  def ord()     return self             end
  #--------------------------------------------------------------------------
  # * even?
  #--------------------------------------------------------------------------
  def even?()   return self % 2 == 0    end
  #--------------------------------------------------------------------------
  # * odd?
  #--------------------------------------------------------------------------
  def odd?()    return self % 2 == 1    end
  #--------------------------------------------------------------------------
  # * odd?
  #--------------------------------------------------------------------------
  def pred()    return self - 1         end
  #--------------------------------------------------------------------------
  # * pow(numeric)
  # * pow(integer, integer)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Integer.html#method-i-pow
  #--------------------------------------------------------------------------
  def pow(*args)
    return self ** args[0] if args.size == 1
    return (self ** args[0]) % args[1] if args.size == 2
    return self
  end
end

#==============================================================================
# ** Float
#==============================================================================

class Float < Numeric
  #--------------------------------------------------------------------------
  INFINITY  = (1.0 / 0.0)
  NAN       = (0.0 / 0.0)
  #--------------------------------------------------------------------------
  # * ceil
  # * ceil(level)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Float.html#method-i-ceil
  #--------------------------------------------------------------------------
  alias ceil_no_level ceil unless $@
  def ceil(level=0)
    return ceil_no_level if level == 0 or level.nil?
    n = self * (10 ** level)
    result = n.ceil_no_level.to_f
    result = result / (10 ** level)
    result = result.ceil_no_level if level < 0
    return result
  end
  #--------------------------------------------------------------------------
  # * floor
  # * floor(level)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Float.html#method-i-floor
  #--------------------------------------------------------------------------
  alias floor_no_level floor unless $@
  def floor(level=0)
    return floor_no_level if level == 0 or level.nil?
    n = self * (10 ** level)
    result = n.floor_no_level.to_f
    result = result / (10 ** level)
    result = result.floor_no_level if level < 0
    return result
  end
  #--------------------------------------------------------------------------
  # * truncate
  # * truncate(level)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Float.html#method-i-truncate
  #--------------------------------------------------------------------------
  alias truncate_no_level truncate unless $@
  def truncate(level=0)
    return truncate_no_level if level == 0 or level.nil?
    n = self * (10 ** level)
    result = n.truncate_no_level.to_f
    result = result / (10 ** level)
    result = result.truncate_no_level if level < 0
    return result
  end
  #--------------------------------------------------------------------------
  # * round([ half ])
  # * round(level, [ half ])
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Float.html#method-i-round
  #--------------------------------------------------------------------------
  # Requiere: Numeric:digit
  # Nota: El argumento half es un simple Symbol
  #   round(:up)  round(:down)  round(:even)
  #--------------------------------------------------------------------------
  alias round_no_level round unless $@
  def round(*args)
    level = 0 ; level = args[0] if args[0].is_a?(Integer)
    sym = :up ; sym = args[-1] if args[-1].is_a?(Symbol)
    return round_no_level if level == 0 && sym == :up
    result = self * (10 ** level)
    case sym
    when :up
      result = result.ceil.to_f  if result.digit(-1) >= 5
      result = result.floor.to_f if result.digit(-1) < 5
    when :down
      result = result.ceil.to_f  if result.digit(-1) > 5
      result = result.floor.to_f if result.digit(-1) <= 5
    when :even
      if result.digit(-1) == 5
        if result.ceil % 2 == 0
          result = result.ceil.to_f
        else
          result = result.floor.to_f
        end
      else
        result = result.round.to_f
      end
    end
    result = result / (10 ** level)
    result = result.round_no_level if level < 0
    result = result.to_i if result == result.to_i
    return result
  end
end

#==============================================================================
# ** Integer
#==============================================================================

class Integer < Numeric
  #--------------------------------------------------------------------------
  # * ceil([level])
  #--------------------------------------------------------------------------
  # Requiere: Float:ceil para usarlo con valor asignado
  #--------------------------------------------------------------------------
  def ceil(level=0)     return self.to_f.ceil(level)      end
  #--------------------------------------------------------------------------
  # * floor([level])
  #--------------------------------------------------------------------------
  # Requiere: Float:floor para usarlo con valor asignado
  #--------------------------------------------------------------------------
  def floor(level=0)    return self.to_f.floor(level)     end
  #--------------------------------------------------------------------------
  # * truncate([level])
  #--------------------------------------------------------------------------
  # Requiere: Float:truncate para usarlo con valor asignado
  #--------------------------------------------------------------------------
  def truncate(level=0) return self.to_f.truncate(level)  end
  #--------------------------------------------------------------------------
  # * round([level])
  #--------------------------------------------------------------------------
  # Requiere: Float:round para usarlo con valor asignado
  #--------------------------------------------------------------------------
  def round(*args)      return self.to_f.round(*args)     end
  #--------------------------------------------------------------------------
  # * digits([base])
  #--------------------------------------------------------------------------
  # Solo se integró parcialmente, puede dar problemas con bases mayores que 10
  #--------------------------------------------------------------------------
  def digits(base=10)
    return self.to_s(base).split(//).reverse.map {|x| x.to_i}
  end
  #--------------------------------------------------------------------------
  # * Integer.sqrt(value)
  #--------------------------------------------------------------------------
  def Integer.sqrt(value)
    return Math.sqrt(value.to_i).floor
  end
  #--------------------------------------------------------------------------
  # * divisors
  #--------------------------------------------------------------------------
  def divisors
    value = self.abs
    result = [1]
    max_div = (value.to_f / 2).floor
    for i in 2..max_div
      result.push(i) if value % i == 0
    end
    result.push(value)
    return result
  end
  #--------------------------------------------------------------------------
  # * factorize
  #--------------------------------------------------------------------------
  def factorize
    value = self.abs
    current_value = value
    result = []
    max_div = (value.to_f / 2).floor
    loop do
      break if current_value == 1
      for i in 2..max_div
        if current_value % i == 0
          current_value /= i
          result.push(i)
          break i
        end
      end
      return [value] if result.size == 0
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * gcd(value)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Integer.html#method-i-gcd
  #--------------------------------------------------------------------------
  # Requiere: Integer:divisors
  #--------------------------------------------------------------------------
  def gcd(value)
    x = self.divisors ; y = value.divisors
    array = [x, y].sort {|a,b| b.length - a.length}
    a = array[0].reverse ; b = array[1].reverse
    for i in 0...a.size
      for j in 0...b.size
        return a[i] if a[i] == b[j]
      end
    end
    return 1
  end
  #--------------------------------------------------------------------------
  # * lcm(value)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Integer.html#method-i-lcm
  #--------------------------------------------------------------------------
  # Requiere: Integer:gcd
  #--------------------------------------------------------------------------
  def lcm(value)
    return (self * value).abs / gcd(value)
  end
  #--------------------------------------------------------------------------
  # * gcdlcm(value)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Integer.html#method-i-gcdlcm
  #--------------------------------------------------------------------------
  # Requiere: Integer:gcd
  #--------------------------------------------------------------------------
  def gcdlcm(value)
    gcd = self.gcd(value)
    lcm = (self * value).abs / gcd
    return [gcd, lcm]
  end
end

#==============================================================================
# ** Kernel
#==============================================================================

module Kernel
  #--------------------------------------------------------------------------
  # * Integer(arg)
  # * Integer(string, base)
  #--------------------------------------------------------------------------
  alias set_int_kernel Integer unless $@
  def Integer(*args)
    return set_int_kernel(*args) if args.size == 1
    return args[0].to_i(args[1])
  end
end

#==============================================================================
# ** Math
#==============================================================================

module Math
  class << self
    #------------------------------------------------------------------------
    # * cbrt(num)
    #------------------------------------------------------------------------
    # https://ruby-doc.org/core-2.5.0/Math.html#method-c-cbrt
    #------------------------------------------------------------------------
    def cbrt(num)
      return (num.abs) ** (1.0 / 3) if num > 0
      return -((num.abs) ** (1.0 / 3))
    end
    #------------------------------------------------------------------------
    # * fact(n)
    #------------------------------------------------------------------------
    def fact(n)
      return (1..n).inject(1) {|r,i| r*i }
    end
    #------------------------------------------------------------------------
    # * gamma(n)
    #------------------------------------------------------------------------
    # https://ruby-doc.org/core-2.5.0/Math.html#method-c-gamma
    #------------------------------------------------------------------------
    # Requiere: Math.fact
    #------------------------------------------------------------------------
    def gamma(n)
      return fact(n-1)
    end
    #------------------------------------------------------------------------
    # * lgamma(n)
    #------------------------------------------------------------------------
    # https://ruby-doc.org/core-2.5.0/Math.html#method-c-lgamma
    #------------------------------------------------------------------------
    # Requiere: Math.gamma
    #------------------------------------------------------------------------
    def lgamma(n)
      [log(gamma(n).abs), gamma(n) < 0 ? -1 : 1]
    end
    #------------------------------------------------------------------------
    # * log(n)
    # * log(n, base)
    #------------------------------------------------------------------------
    # https://ruby-doc.org/core-2.5.0/Math.html#method-c-log
    #------------------------------------------------------------------------
    alias log_no_base log unless $@
    def log(n, base=10)
      return log_no_base(n) if base == 10
      return log10(n) / log10(base)
    end
    #------------------------------------------------------------------------
    # * log2(n)
    #------------------------------------------------------------------------
    # https://ruby-doc.org/core-2.5.0/Math.html#method-c-log
    #------------------------------------------------------------------------
    # Requiere: Math.log
    #------------------------------------------------------------------------
    def log2(n)
      return log(n, 2)
    end
  end
end

Pronto subiré alguno más.
avatar
Wecoc
Administrador
Administrador



Créditos 12291

Gracias : 646

Volver arriba Ir abajo

RPG Maker XP Re: [XP] Colección de Snippets para RPG maker

Mensaje por Wecoc el 2018-01-15, 20:34

Vengo a subir dos más, uno bastante sencillo (Hash) y uno algo especial (Regexp).

Atención: Tal como mencioné, en los scripts de ésta colección se pueden usar los métodos sueltos (excepto en casos que ya se especifican), no necesitáis copiar todo el script para usar solo unos pocos métodos en vuestros scripts. Regexp es una excepción, si se usa sí se requiere entero ya que los métodos están muy entremezclados.

Código:
#==============================================================================
# ** [XP] rb2RGSS (Ruby Methods to RGSS) - Hash
#------------------------------------------------------------------------------
# PARTE 4. Hash                                                   Versión: 1.0
# Autor: Wecoc (libre de uso)                                       15/01/2017
#------------------------------------------------------------------------------
# Ésta colección define algunos métodos que por defecto no están disponibles en
# RPG maker XP pero sí en la versión 2.5 de Ruby.
#------------------------------------------------------------------------------
# Puede obtenerse información y ejemplos de uso en la guía de Ruby:
# https://ruby-doc.org/core-2.5.0/Hash.html
#==============================================================================

#==============================================================================
# * Nuevos sinónimos de métodos existentes
#==============================================================================
# keep_if
# to_hash
#==============================================================================
# * Nuevos métodos
#==============================================================================
# > | >= | < | <=
# assoc
# rassoc
# compact
# compact!
# default_proc=
# dig
# fetch_values
# flatten
# key
# select!
# slice
# to_h
# transform_keys
# transform_keys!
# transform_values
# transform_values!
#==============================================================================
# * Reescritura de métodos ya existentes
#==============================================================================
# select    (resultado en formato Hash)
#==============================================================================
# * Especiales
#==============================================================================
# Hash.try_convert
# Hash
#==============================================================================

#==============================================================================
# ** Hash
#==============================================================================

class Hash
  #--------------------------------------------------------------------------
  # * Hash.try_convert(value)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-c-try_convert
  #--------------------------------------------------------------------------
  def Hash.try_convert(value)
    return value.to_h rescue nil
  end
  #--------------------------------------------------------------------------
  # * hash > other
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-3E
  #--------------------------------------------------------------------------
  def >(other)
    return false if self.size <= other.size
    for k in other.keys
      return false if !self.keys.include?(k)
    end
    return true
  end
  #--------------------------------------------------------------------------
  # * hash >= other
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-3E-3D
  #--------------------------------------------------------------------------
  def >=(other)
    return true if self == other
    return (self > other)
  end
  #--------------------------------------------------------------------------
  # * hash < other
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-3C
  #--------------------------------------------------------------------------
  def <(other)
    return (other > self)
  end
  #--------------------------------------------------------------------------
  # * hash <= other
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-3C-3D
  #--------------------------------------------------------------------------
  def <=(other)
    return (other >= self)
  end
  #--------------------------------------------------------------------------
  alias_method(:keep_if, :select)
  #--------------------------------------------------------------------------
  # * assoc(obj)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-assoc
  #--------------------------------------------------------------------------
  def assoc(value)
    return self.to_a.assoc(value)
  end
  #--------------------------------------------------------------------------
  # * rassoc(obj)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-rassoc
  #--------------------------------------------------------------------------
  def rassoc(obj)
    for k in self.keys
      return [k, self[k]] if k == obj || self[k] == obj
    end
    return nil
  end
  #--------------------------------------------------------------------------
  # * compact
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-compact
  #--------------------------------------------------------------------------
  def compact
    cloned = self.clone
    for k in cloned.keys
      cloned.delete(k) if cloned[k].nil?
    end
    return cloned
  end
  #--------------------------------------------------------------------------
  # * compact!
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-compact
  #--------------------------------------------------------------------------
  def compact!
    result = self.compact
    self.replace(result)
    return self
  end
  #--------------------------------------------------------------------------
  # * default_proc = proc
  # * default_proc = nil
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-default_proc
  #--------------------------------------------------------------------------
  def default_proc=(proc)
    result = Hash.new(&proc)
    for k in self.keys
      result[k] = self[k]
    end
    self.replace(result)
    return self
  end
  #--------------------------------------------------------------------------
  # * dig(key, ...)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-dig
  #--------------------------------------------------------------------------
  def dig(*args)
    count = 0
    result = self
    loop do
      result = result[args[count]]
      return nil if result.nil?
      count += 1
      break if count == args.size
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * fetch_values(key, ...)
  # * fetch_values(key, ...) { |key| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-fetch_values
  #--------------------------------------------------------------------------
  def fetch_values(*args, &block)
    result = []
    for i in 0...args.size
      k = args[i]
      if self.keys.include?(k)
        result.push(self[k])
      else
        if block_given?
          result.push(yield k)
        else
          k = k.inspect ; h = self.inspect
          raise ArgumentError, "Undefined key #{k} for Hash #{h}"
        end
      end
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * flatten
  # * flatten(level)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-flatten
  #--------------------------------------------------------------------------
  # Requiere: Array:flatten para usarlo con valor asignado
  #--------------------------------------------------------------------------
  def flatten(level=1)
    array = self.to_a
    return self.to_a.flatten(level) if array.method(:flatten).arity == -1
    result = []
    for k in self.keys
      result.push(k)
      result.push(self[k])
    end
    result.flatten! if level > 1
    return result
  end
  #--------------------------------------------------------------------------
  # * key(value)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-key
  #--------------------------------------------------------------------------
  def key(value)
    for k in self.keys
      return k if self[k] == value
    end
    return nil
  end
  #--------------------------------------------------------------------------
  # * select {|key, value| block}
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-select
  #--------------------------------------------------------------------------
  # Requiere: Array:to_h para que el resultado esté en formato Hash
  #--------------------------------------------------------------------------
  alias select_as_array select unless $@
  def select(&block)
    array = select_as_array(&block)
    array = array.to_h if Array.method_defined?(:to_h)
    return array
  end
  #--------------------------------------------------------------------------
  # * select! {|key, value| block}
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-select
  #--------------------------------------------------------------------------
  # Requiere: Array:to_h
  # Requiere: Hash:select
  #--------------------------------------------------------------------------
  def select!(&block)
    result = self.select(&block)
    self.replace(result) if result.is_a?(Hash)
    return self
  end
  #--------------------------------------------------------------------------
  # * slice(*keys)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-slice
  #--------------------------------------------------------------------------
  def slice(*args)
    result = Hash.new
    for i in 0...args.size
      k = args[i]
      result[k] = self[k]
    end
    return result
  end
  #--------------------------------------------------------------------------
  def to_h() self end
  alias_method(:to_hash, :to_h)
  #--------------------------------------------------------------------------
  # * transform_keys {|key| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-transform_keys
  #--------------------------------------------------------------------------
  def transform_keys(&block)
    for k in self.keys
      value = self[k]
      delete(k)
      self[(yield k)] = value
    end
    return self
  end
  #--------------------------------------------------------------------------
  # * transform_keys! {|key| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-transform_keys
  #--------------------------------------------------------------------------
  def transform_keys!(&block)
    self.replace(self.transform_keys(&block))
  end
  #--------------------------------------------------------------------------
  # * transform_values {|value| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-transform_values
  #--------------------------------------------------------------------------
  def transform_values(&block)
    for k in self.keys
      value = self[k]
      self[k] = (yield value)
    end
    return self
  end
  #--------------------------------------------------------------------------
  # * transform_values! {|value| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Hash.html#method-i-transform_values
  #--------------------------------------------------------------------------
  def transform_values!(&block)
    self.replace(self.transform_values(&block))
  end
end

#==============================================================================
# ** Kernel
#==============================================================================

module Kernel
  #--------------------------------------------------------------------------
  # * Hash(arg)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Kernel.html#method-i-Hash
  #--------------------------------------------------------------------------
  # Requiere: Array:to_h
  # Requiere: Hash:to_h
  #--------------------------------------------------------------------------
  def Hash(arg)
    return arg.to_h
  end
end

Código:
#==============================================================================
# ** [XP] rb2RGSS (Ruby Methods to RGSS) - Regexp
#------------------------------------------------------------------------------
# PARTE 5. Regexp                                                Versión: 1.2
# Autor: Wecoc (libre de uso)                                      01/02/2017
#------------------------------------------------------------------------------
# Ésta colección define algunos métodos que por defecto no están disponibles en
# RPG maker XP pero sí en la versión 2.5 de Ruby.
#------------------------------------------------------------------------------
# Puede obtenerse información y ejemplos de uso en la guía de Ruby:
# https://ruby-doc.org/core-2.5.0/Regexp.html
#==============================================================================
# ATENCIÓN: Todos los métodos siguientes deben ir juntos para funcionar bien
#------------------------------------------------------------------------------
# El nuevo método rb_match funciona como match pero con opciones de formato de
# Regexp no disponibles en RGSS pero sí en Ruby, como el uso de ?<etiquetas>
#------------------------------------------------------------------------------
# Para que rb_match almacene la información del último match en la variable $~
# y Regexp.last_match, debe llamarse usando 'binding' como último argumento.
#      V. default:    /./.match("A")
#      V. extendida:  /./.rb_match("A", binding)
# Ocurre lo mismo con rb_match_against.
#      V. default:    /./ =~ ("A")
#      V. extendida:  /./.rb_match_against("A", binding)
#------------------------------------------------------------------------------
# Se pueden obtener variables locales partiendo de un rb_match, pero éstas
# deben ser definidas previamente con un valor por defecto:
#      dollars = nil ; cents = nil
#      /\$(?<dollars>\d+)\.(?<cents>\d+)/.rb_match("$3.67", binding)
#      p dollars, cents #=> "3", "64"
#==============================================================================

#==============================================================================
# * Nuevas métodos con funciones ya existentes (Regexp)
#==============================================================================
# match  -> rb_match  (con argumentos de posición y binding)
# match? -> rb_match? (con argumentos de posición y binding)
# =~ -> rb_match_against (con argumentos de posición y binding)
#==============================================================================
# * Nuevos métodos (Regexp)
#==============================================================================
# named_captures
# names
#==============================================================================
# * Especiales
#==============================================================================
# Regexp.try_convert
# Regexp.union
# Regexp.last_match
#==============================================================================

#==============================================================================
# * Nuevos métodos (MatchData)
#==============================================================================
# regexp (interno)
# parameters (interno)
# named_captures
# names
#==============================================================================
# * Nuevas funciones a métodos ya existentes (MatchData)
#==============================================================================
# []        (con String o Symbol como argumento)
# inspect  (con los resultados y parámetros visibles)
# offset    (con String o Symbol como argumento)
# begin    (con String o Symbol como argumento)
# end      (con String o Symbol como argumento)
# values_at (con String o Symbol como argumento)
#==============================================================================

#==============================================================================
# * Nuevas métodos con funciones ya existentes (String)
#==============================================================================
# match  -> rb_match  (con argumentos de posición y binding)
# match? -> rb_match? (con argumentos de posición y binding)
# =~ -> rb_match_against (con argumentos de posición y binding)
#------------------------------------------------------------------------------
# []        (con Regexp como argumento)
# []=      (con Regexp como argumento)
# slice    (con Regexp como argumento)
# slice!    (con Regexp como argumento)
# gsub      (con Regexp como 1r argumento, con Hash como 2o argumento)
# gsub!    (con Regexp como 1r argumento, con Hash como 2o argumento)
# sub      (con Regexp como 1r argumento, con Hash como 2o argumento)
# sub!      (con Regexp como 1r argumento, con Hash como 2o argumento)
#==============================================================================

#==============================================================================
# ** Regexp
#==============================================================================

class Regexp
  #--------------------------------------------------------------------------
  # * Regexp.try_convert(value)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Regexp.html#method-c-try_convert
  #--------------------------------------------------------------------------
  def Regexp.try_convert(value)
    return value if value.is_a?(Regexp)
    return nil
  end
  #--------------------------------------------------------------------------
  # * Regexp.union(pat1, pat2, ...)
  # * Regexp.union(pats_ary)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Regexp.html#method-c-union
  #--------------------------------------------------------------------------
  class << self
    alias union_no_ary union unless $@
    def union(*args)
      return union_no_ary(*args[0]) if args[0].is_a?(Array)
      return union_no_ary(*args)
    end
  end
  #--------------------------------------------------------------------------
  # * match(str) -> rb_match(str, binding)
  # *              rb_match(str, pos, binding)
  #--------------------------------------------------------------------------
  # Se ha tenido que crear como método a parte porque el :match original no
  # se puede sobreescribir directamente.
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Regexp.html#method-i-match
  #--------------------------------------------------------------------------
  def rb_match(str, *args)
    pos = args[0].is_a?(Binding) ? 0 : args[0]
    cb = args[-1].is_a?(Binding) ? args[-1] : binding
    return eval("#{self.inspect}.match(#{str.inspect})", cb) if pos.nil?
    return eval("#{self.inspect}.match(#{str[pos..str.size].inspect})", cb)
  end
  #--------------------------------------------------------------------------
  def rb2rgss_format(*args)
    result = self.clone
    str = rb2rgss_format_str(self.to_s, *args)
    return Regexp.new(str, self.options)
  end
  #··········································································
  def rb2rgss_format_str(str, *args)
    @parameters = []
    @par_meanings = {}
    param_reg = /\((\?[<|'].+?[>|'])(.+?)\)/
    loop do
      param_match = param_reg.match(str)
      break if param_match.nil?
      param = param_match[1]
      str.sub!(param, "")
      param_sym = param[2..param.size-2].to_sym
      @parameters.push(param_sym)
      @par_meanings[param_sym] = param_match[2]
    end
    cloned = str.clone
    for k in @par_meanings.keys
      unless @par_meanings[k].nil?
        cloned.gsub!(/\\k<#{k}>/, "(#{@par_meanings[k]})")
        cloned.gsub!(/\\g<#{k}>/, "(#{@par_meanings[k]})")
      end
    end
    r = Regexp.new(cloned, self.options)
    current_str = args.shift
    if current_str.nil?
      param_match = r.match(str).to_a
    else
      param_match = r.no_format_rb_match(current_str, *args).to_a
    end
    n = named_captures
    for k in @par_meanings.keys
      m = n[k.to_s]
      for i in m
        unless param_match[i].nil?
          str.gsub!(/\\k<#{k}>/, param_match[i])
        end
      end
    end
    i = 1
    loop do
      i += 1
      param_g = /\\g<#{k}>/.match(str)
      break if param_g.nil? or param_match[i].nil?
      str.sub!(/\\g<#{k}>/, param_match[i])
    end
    return str
  end
  #··········································································
  PARAM_POSIX = {
    "Alnum" => ":alnum:", "Alpha" => ":alpha:", "Blank" => ":blank:",
    "Cntrl" => ":cntrl:", "Digit" => ":digit:", "Graph" => ":graph:",
    "Lower" => ":lower:", "Print" => ":print:", "Punct" => ":punct:",
    "Space" => ":space:", "Upper" => ":upper:", "XDigit" => ":xdigit:",
    "ASCII" => ":ascii:", "Word"  => "a-zA-Z0-9_"
  }
  alias rb2rgss_format_posix rb2rgss_format_str unless $@
  def rb2rgss_format_str(str, *args)
    str = rb2rgss_format_posix(str, *args)
    if /\\p/.match(str)
      str.gsub!(/\\p{Any}/, ".")
      str.gsub!(/\\p{^Any}/, "")
      for par in PARAM_POSIX.keys
        loop do
          param_reg = /\\p\{(\^?)#{par}\}/
          param_match = param_reg.match(str)
          break if param_match.nil?
          param = param_match[0]
          str.sub!(param, "[#{param_match[1]}[#{PARAM_POSIX[par]}]]")
        end
      end
    end
    return str
  end
  #··········································································
  def parameters
    return [] if @parameters.nil?
    return @parameters
  end
  #··········································································
  alias no_format_rb_match rb_match unless $@
  def rb_match(str, *args)
    if block_given?
      result = (yield rb2rgss_format(str, *args).no_format_rb_match(str, *args))
    else
      result = rb2rgss_format(str, *args).no_format_rb_match(str, *args)
    end
    unless result.nil?
      result.instance_eval("@regexp = #{self.inspect}")
      result.instance_eval("@parameters = #{self.parameters.inspect}")
      cb = args[-1].is_a?(Binding) ? args[-1] : binding
      for sym in self.parameters
        eval("#{sym} = #{result[sym].inspect}", cb)
      end
    end
    return result
  end
  #··········································································
  alias rgss_equality === unless $@
  def ===(other)
    other = other.rb2rgss_format if other.is_a?(Regexp)
    return rb2rgss_format.rgss_equality(other)
  end
  #--------------------------------------------------------------------------
  # * self =~ obj -> rb_match_against(obj, binding)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Regexp.html#method-i-3D-7E
  #--------------------------------------------------------------------------
  def rb_match_against(other, cb=nil)
    cb = binding if cb.nil?
    other = other.rb2rgss_format if other.is_a?(Regexp)
    current = rb2rgss_format(other)
    current.rb_match(other, cb)
    return current =~ other
  end
  #--------------------------------------------------------------------------
  # * match?(str) -> rb_match?(str, binding)
  # *                rb_match?(str, pos, binding)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Regexp.html#method-i-match
  #--------------------------------------------------------------------------
  def match?(*args)
    return !self.match(*args).nil?
  end
  #··········································································
  def rb_match?(str, *args)
    return !self.rb_match(str, *args).nil?
  end
  #--------------------------------------------------------------------------
  # * named_captures
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Regexp.html#method-i-named_captures
  #--------------------------------------------------------------------------
  def named_captures
    return @named_captures if !@named_captures.nil?
    result = Hash.new
    all_reg  = /\(.+?\)/
    param_reg = /\?<.+?>/
    str = self.inspect
    i = 0
    loop do
      param = all_reg.match(str)
      break if param.nil?
      param = param[0]
      str.sub!(param, "")
      i += 1
      param = param_reg.match(param)
      next if param.nil?
      param = param[0]
      param_sym = param[2..param.size-2].to_sym
      if result.keys.include?(param_sym.to_s)
        result[param_sym.to_s].push i
      else
        result[param_sym.to_s] = [i]
      end
    end
    @named_captures = result.clone
    return @named_captures
  end
  #--------------------------------------------------------------------------
  # * names
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/Regexp.html#method-i-names
  #--------------------------------------------------------------------------
  def names
    result = []
    n = self.named_captures
    for i in 0...n.keys.size
      k = n.keys[i]
      s = n[k].to_a[0]
      result[s] = k
    end
    return result.compact
  end
end

#==============================================================================
# ** MatchData
#==============================================================================

class MatchData
  #--------------------------------------------------------------------------
  attr_reader :regexp
  #--------------------------------------------------------------------------
  def parameters
    return [] if @parameters.nil?
    return @parameters
  end
  #--------------------------------------------------------------------------
  # * [i]
  # * [start, length]
  # * [range]
  # * [name]
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/MatchData.html#method-i-5B-5D
  #--------------------------------------------------------------------------
  alias get_internal_par [] unless $@
  def [](*args)
    if args[0].is_a?(String) || args[0].is_a?(Symbol)
      return nil if regexp.nil?
      name = args[0].to_s
      value = self.regexp.named_captures[name]
      return nil if value.nil?
      return get_internal_par(value[0])
    else
      return get_internal_par(*args)
    end
  end
  #--------------------------------------------------------------------------
  # * named_captures
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/MatchData.html#method-i-named_captures
  #--------------------------------------------------------------------------
  def named_captures
    result = Hash.new
    for i in 0...self.parameters.size
      param = self.parameters[i]
      result[param.to_s] = self[i+1]
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * names
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/MatchData.html#method-i-names
  #--------------------------------------------------------------------------
  def names
    return [] if regexp.nil?
    regexp.names
  end
  #--------------------------------------------------------------------------
  # * inspect
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/MatchData.html#method-i-inspect
  #--------------------------------------------------------------------------
  def inspect
    result = "#<MatchData \"#{self.to_a[0]}\""
    for i in 0...captures.size
      result.concat " "
      c = captures[i]
      val = i+1
      unless regexp.nil?
        n = regexp.named_captures
        for k in n.keys
          if n[k].include?(i+1)
            val = k.to_s
            break k
          end
        end
      end
      if !c.nil?
        result.concat "#{val}:\"#{c}\""
      else
        result.concat "#{val}:nil"
      end
    end
    result.concat ">"
    return result
  end
  #--------------------------------------------------------------------------
  # * offset(obj)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/MatchData.html#method-i-offset
  #--------------------------------------------------------------------------
  alias offset_no_sym offset unless $@
  def offset(obj)
    return offset_no_sym(obj) if obj.is_a?(Numeric)
    return [] if regexp.nil?
    return [] if !regexp.named_captures.keys.include?(obj.to_s)
    value = regexp.named_captures[obj.to_s][0]
    return [] if value == nil
    return offset_no_sym(value)
  end
  #··········································································
  def begin(obj)  return offset(obj)[0]  end
  def end(obj)    return offset(obj)[1]  end
  #--------------------------------------------------------------------------
  # * values_at([index]*)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/MatchData.html#method-i-values_at
  #--------------------------------------------------------------------------
  alias values_at_int values_at unless $@
  def values_at(*args)
    values = []
    for i in 0...args.size
      val = args[i]
      if val.is_a?(String) || val.is_a?(Symbol)
        val = regexp.named_captures[val.to_s][0]
      end
      values.push(val)
    end
    values_at_int(*values)
  end
end

#==============================================================================
# ** String
#==============================================================================

class String
  #--------------------------------------------------------------------------
  # * [index]
  # * [start, length]
  # * [range]
  # * [regexp]
  # * [regexp, capture]
  # * [match_str]
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-5B-5D
  #--------------------------------------------------------------------------
  alias get_index_ini [] unless $@
  def [](*args)
    n = args[0]
    if args.size == 1 && n.is_a?(Integer)
      return nil if n >= self.size || n < -self.size - 1
      return get_index_ini(n..n)
    end
    if n.is_a?(Integer) || n.is_a?(Range) || n.is_a?(String)
      return get_index_ini(*args)
    end
    capture = args[1]
    if n.is_a?(Regexp)
      return get_index_ini(*args) if (capture.is_a?(Integer) || capture.nil?)
      return get_index_ini(n, n.named_captures[capture.to_s][0])
    end
    return n.match(self)[capture]
  end
  #--------------------------------------------------------------------------
  # * [index] = str
  # * [start, length] = str
  # * [range] = str
  # * [regexp] = str
  # * [regexp, capture] = str
  # * [match_str] = str
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-5B-5D-3D
  #--------------------------------------------------------------------------
  alias set_index_ini []= unless $@
  def []=(*args)
    n = args[0]
    value = args[-1]
    if n.is_a?(Integer) || n.is_a?(Range) || n.is_a?(String)
      return set_index_ini(*args)
    end
    capture = args[1]
    capture = nil if args.size == 2
    if n.is_a?(Regexp)
      return set_index_ini(*args) if (capture.is_a?(Integer) || capture.nil?)
      return set_index_ini(n, n.named_captures[capture.to_s][0], value)
    end
    return set_index_ini(n, n.named_captures[capture.to_s][0], value)
  end
  #--------------------------------------------------------------------------
  # * slice(index)
  # * slice(start, length)
  # * slice(range)
  # * slice(regexp)
  # * slice(regexp, capture)
  # * slice(match_str)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-slice
  #--------------------------------------------------------------------------
  def slice(*args)
    return self[*args]
  end
  #--------------------------------------------------------------------------
  # * slice!(index)
  # * slice!(start, length)
  # * slice!(range)
  # * slice!(regexp)
  # * slice!(regexp, capture)
  # * slice!(match_str)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-slice
  #--------------------------------------------------------------------------
  alias slice_no_par slice! unless $@
  def slice!(*args)
    return slice_no_par(*args) if !args[0].is_a?(Regexp)
    regexp = args[0]
    return slice_no_par(*args) if regexp.names.size == 0
    result = self.slice(*args)
    index = self.index(result)
    slice_no_par(index, result.size)
    return result
  end
  #--------------------------------------------------------------------------
  # * gsub(pattern, replacement)
  # * gsub(pattern, hash)
  # * gsub(pattern) {|match| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-gsub
  #--------------------------------------------------------------------------
  alias gsub_no_par gsub unless $@
  def gsub(*args, &block)
    return gsub_no_par(*args, &block) if args[0].is_a?(String)
    regexp = args[0]
    return gsub_no_par(*args, &block) if regexp.names.size == 0
    result = args.clone
    for str in result[1..result.size]
      for k in regexp.named_captures.keys
        i = regexp.named_captures[k][0]
        str.gsub!("\k<#{k}>", i.to_s)
      end
    end
    return gsub_no_par(*result, &block)
  end
  #··········································································
  alias gsub_no_hash gsub unless $@
  def gsub(*args, &block)
    return gsub_no_hash(*args, &block) unless args[1].is_a?(Hash)
    regexp, hash = *args
    result = self.clone
    for k in hash.keys
      result.gsub!(k, hash[k].to_s) unless regexp.match(k).nil?
    end
    result.gsub!(regexp, "")
    return result
  end
  #··········································································
  def gsub!(*args, &block)
    result = self.gsub(*args, &block)
    return nil if self == result
    return self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * sub(pattern, replacement)
  # * sub(pattern, hash)
  # * sub(pattern) {|match| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-gsub
  #--------------------------------------------------------------------------
  alias sub_no_par sub unless $@
  def sub(*args, &block)
    return sub_no_par(*args, &block) if args[0].is_a?(String)
    regexp = args[0]
    return sub_no_par(*args, &block) if regexp.names.size == 0
    result = args.clone
    for str in result[1..result.size]
      for k in regexp.named_captures.keys
        i = regexp.named_captures[k][0]
        str.sub!("\k<#{k}>", i.to_s)
      end
    end
    return sub_no_par(*result, &block)
  end
  #··········································································
  alias sub_no_hash sub unless $@
  def sub(*args, &block)
    return sub_no_hash(*args, &block) unless args[1].is_a?(Hash)
    regexp, hash = *args
    result = self.clone
    matched = false
    for k in hash.keys
      unless regexp.match(k).nil?
        result.sub!(k, hash[k].to_s)
        matched = true
        break
      end
    end
    result.sub!(regexp, "") if matched == false
    return result
  end
  #··········································································
  def sub!(*args, &block)
    result = self.sub(*args, &block)
    return nil if self == result
    return self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * match(pattern) -> rb_match(pattern, binding)
  # *                  rb_match(pattern, pos, binding)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-match
  #--------------------------------------------------------------------------
  def rb_match(pattern, *args)
    pattern = Regexp.new(pattern) unless pattern.is_a?(Regexp)
    return pattern.rb_match(self, *args)
  end
  #--------------------------------------------------------------------------
  # * match?(pattern) -> rb_match?(pattern, binding)
  # *                    rb_match?(pattern, pos, binding)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-match
  #--------------------------------------------------------------------------
  def match?(pattern)
    return !self.match(pattern).nil?
  end
  #··········································································
  def rb_match?(pattern, *args)
    return !self.rb_match(pattern, *args).nil?
  end
  #--------------------------------------------------------------------------
  # * self =~ obj -> rb_match_against(obj, binding)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-3D-7E
  #--------------------------------------------------------------------------
  def rb_match_against(other, cb=nil)
    cb = binding if cb.nil?
    other = other.rb2rgss_format if other.is_a?(Regexp)
    self.rb_match(other, cb)
    return self =~ other
  end
end

Como ayuda adicional os paso un link que permite crear Regexp fácilmente: Regex101
No tiene opción Ruby pero sí Python, que es muy parecido y el Regexp va igual, así que os servirá.

Pronto subiré alguno más.


Última edición por Wecoc el 2018-02-01, 19:00, editado 3 veces
avatar
Wecoc
Administrador
Administrador



Créditos 12291

Gracias : 646

Volver arriba Ir abajo

RPG Maker XP Re: [XP] Colección de Snippets para RPG maker

Mensaje por Wecoc el 2018-01-18, 03:48

Ya he hecho el de String, un plato fuerte (el doble que los demás) puesto que en Ruby 2.5 tiene muchas cosas que el RGSS no permite. Esta ampliación tiene mejor soporte de carácteres especiales y algunos métodos que con suerte os harán la vida más fácil a la hora de trabajar con String.

También permite usar Regexp en métodos en los que solo se podía usar String, por lo que el script anterior seguramente también os irá bien en éste caso.

Código:
#==============================================================================
# ** [XP] rb2RGSS (Ruby Methods to RGSS) - String
#------------------------------------------------------------------------------
# PARTE 6. String                                                 Versión: 1.0
# Autor: Wecoc (libre de uso)                                       18/01/2017
#------------------------------------------------------------------------------
# Ésta colección define algunos métodos que por defecto no están disponibles en
# RPG maker XP pero sí en la versión 2.5 de Ruby.
#------------------------------------------------------------------------------
# Puede obtenerse información y ejemplos de uso en la guía de Ruby:
# https://ruby-doc.org/core-2.5.0/String.html
#------------------------------------------------------------------------------
# Tabla de carácteres UTF8:
# http://www.fileformat.info/info/charset/UTF-8/list.htm
#==============================================================================

#==============================================================================
# * Nuevos métodos
#==============================================================================
# casecmp?
# clear
# delete_prefix
# delete_prefix!
# delete_suffix
# delete_suffix!
# start_with?
# end_with?
# encoding
# encode
# force_encoding
# bytes
# chars
# ascii_only?
# bytesize
# charsize
# byteslice
# charslice
# charslice!
# charindex
# codepoints
# each_char
# each_codepoint
# lines
# getbyte
# setbyte
# b
# ord
# plain
# plain!
# valid_char?
# valid_encoding?
# partition
# rpartition
# undump
# scrub
# scrub!
#==============================================================================
# * Nuevas funciones a métodos ya existentes
#==============================================================================
# %           (argumento como Hash)
# chr         (bugfix charas especiales)
# concat      (con múltiples argumentos)
# prepend     (con múltiples argumentos)
# downcase    (bugfix charas especiales + opción encoding)
# downcase!   (bugfix charas especiales + opción encoding)
# upcase      (bugfix charas especiales + opción encoding)
# upcase!     (bugfix charas especiales + opción encoding)
# capitalize  (bugfix charas especiales + opción encoding)
# capitalize! (bugfix charas especiales + opción encoding)
# swapcase    (bugfix charas especiales + opción encoding)
# swapcase!   (bugfix charas especiales + opción encoding)
# reverse     (bugfix charas especiales + opción encoding)
# reverse!    (bugfix charas especiales + opción encoding)
# chop        (bugfix charas especiales)
# chop!       (bugfix charas especiales)
# sum         (bugfix charas especiales)
#==============================================================================
# * Métodos para Symbol apdaptados de String
#==============================================================================
# []
# =~
# capitalize
# downcase
# swapcase
# upcase
# casecmp
# casecmp?
# empty?
# match
# match?
# succ
# size
# slice
# to_proc
#==============================================================================
# * Especiales
#==============================================================================
# String.to_widechar
# String.to_multibyte
# String.try_convert
#==============================================================================

#==============================================================================
# * String
#==============================================================================

class String
  #--------------------------------------------------------------------------
  CP_ACP   = 0       # ANSI
  CP_OEM   = 1       # OEM
  CP_UTF8  = 65001   # UTF-8
  #--------------------------------------------------------------------------
  MB2WC = Win32API.new('kernel32', 'MultiByteToWideChar', 'ILPIPI', 'L')
  WC2MB = Win32API.new('kernel32', 'WideCharToMultiByte', 'ILPIPIPP', 'L')
  #--------------------------------------------------------------------------
  def self.to_widechar(str, codepage)
    length = MB2WC.call(codepage, 0, str, -1, nil, 0)
    unless length.zero?
      b = "\x00" * (length << 1)
      unless (MB2WC.call(codepage, 0, str, -1, b, length)).zero?
        return b[0...(b.size-1)]
      else
        return ""
      end
    else
      return ""
    end
  end
  #--------------------------------------------------------------------------
  def self.to_multibyte(str, codepage)
    length = WC2MB.call(codepage, 0, str, -1, nil, 0, nil, nil)
    unless length.zero?
      b = "\x00" * length
      unless (WC2MB.call(codepage, 0, str, -1, b, b.size, nil, nil)).zero?
        return b[0...(b.size-1)]
      else
        return ""
      end
    else
      return ""
    end
  end
  #--------------------------------------------------------------------------
  # * String.try_convert(value)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-c-try_convert
  #--------------------------------------------------------------------------
  def String.try_convert(value)
    return nil if value.is_a?(Regexp)
    return value.to_s rescue nil
  end
  #--------------------------------------------------------------------------
  # * str % arg
  #--------------------------------------------------------------------------
  alias format_setter_int % unless $@
  def %(obj)
    return format_setter_int(obj) unless obj.is_a?(Hash)
    result = self.clone
    cloned = self.clone
    loop do
      param = /%{.+?}/.match(cloned)
      break if param.nil?
      param = param[0]
      cloned.sub!(param, "")
      param_sym = param[2..param.size-2].to_sym
      value = obj[param_sym]
      result.sub!(param, value)
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * casecmp?(other_str)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-casecmp
  #--------------------------------------------------------------------------
  def casecmp?(str)
    return casecmp(str) == 0
  end
  #--------------------------------------------------------------------------
  # * chr [ Versión sin usar str.chars (desfasada) ]
  #--------------------------------------------------------------------------
  #def chr
  #  return self[0..0]
  #end
  #--------------------------------------------------------------------------
  # * clear
  #--------------------------------------------------------------------------
  def clear
    self.replace("")
  end
  #--------------------------------------------------------------------------
  # * concat(obj1, obj2,...)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-concat
  #--------------------------------------------------------------------------
  alias concat_single concat unless $@
  def concat(*args)
    result = []
    for i in 0...args.size
      value = args[i].clone rescue args[i]
      result.concat(value)
    end
    for i in 0...result.size
      concat_single(result[i])
    end
    return self
  end
  #--------------------------------------------------------------------------
  # * prepend(obj1, obj2,...)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-prepend
  #--------------------------------------------------------------------------
  def prepend_single(obj)
    obj = obj.chr if obj.is_a?(Numeric)
    self.insert(0, obj)
  end
  def prepend(*args)
    result = []
    for i in 0...args.size
      value = args[i].clone rescue args[i]
      result.concat(value)
    end
    result.reverse!
    for i in 0...result.size
      prepend_single(result[i])
    end
    return self
  end
  #--------------------------------------------------------------------------
  # * delete_prefix(prefix)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-delete_prefix
  #--------------------------------------------------------------------------
  def delete_prefix(prefix)
    result = self.clone
    return self unless result[0...prefix.size] == prefix
    return result[prefix.size...result.size]
  end
  #--------------------------------------------------------------------------
  # * delete_prefix!(prefix)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-delete_prefix
  #--------------------------------------------------------------------------
  def delete_prefix!(prefix)
    result = self.delete_prefix(prefix)
    return nil if self == result
    self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * delete_suffix(suffix)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-delete_suffix
  #--------------------------------------------------------------------------
  def delete_suffix(suffix)
    result = self.clone
    s = result.size - suffix.size
    return self unless result[s...result.size] == suffix
    return result[0...s]
  end
  #--------------------------------------------------------------------------
  # * delete_suffix!(suffix)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-delete_suffix!
  #--------------------------------------------------------------------------
  def delete_suffix!(suffix)
    result = self.delete_suffix(suffix)
    return nil if self == result
    self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * start_with?([prefixes]+)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-start_with-3F
  #--------------------------------------------------------------------------
  def start_with?(prefix)
    return self[0...prefix.size] == prefix
  end
  alias start_with_single? start_with? unless $@
  def start_with?(*args)
    for i in 0...args.size
      return true if self.start_with_single?(args[i])
    end
    return false
  end
  #--------------------------------------------------------------------------
  # * end_with?([suffixes]+)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-end_with-3F
  #--------------------------------------------------------------------------
  def end_with?(suffix)
    s = self.size - suffix.size
    return self[s...self.size] == suffix
  end
  alias end_with_single? end_with? unless $@
  def end_with?(*args)
    for i in 0...args.size
      return true if self.end_with_single?(args[i])
    end
    return false
  end
  #--------------------------------------------------------------------------
  # * encoding
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-encoding
  #--------------------------------------------------------------------------
  def encoding
    @encoding = "UTF-8" if @encoding.nil?
    return @encoding
  end
  #--------------------------------------------------------------------------
  # * encode(encoding)
  # * encode(dst_encoding, src_encoding
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-encode
  #--------------------------------------------------------------------------
  def encode(*args)
    dst = args[0]
    src = args[1]
    src = self.encoding unless src.is_a?(String)
    return self if dst == src
    @encoding = src
    return self.clone.force_encoding(dst)
  end
  #--------------------------------------------------------------------------
  # * encode!(encoding)
  # * encode!(dst_encoding, src_encoding
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-encode
  #--------------------------------------------------------------------------
  def encode!(*args)
    result = self.encode(*args)
    return nil if self == result
    return self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * force_encoding(dst)
  #--------------------------------------------------------------------------
  def force_encoding(dst)
    dst_int = case dst
      when "ANSI":  CP_ACP
      when "OEM":   CP_OEM
      when "UTF-8": CP_UTF8
      else; dst
    end
    src_int = case self.encoding
      when "ANSI":  CP_ACP
      when "OEM":   CP_OEM
      when "UTF-8": CP_UTF8
      else; self.encoding
    end
    return self if dst_int.nil? or src_int.nil?
    widechar = String.to_widechar(self, src_int)
    self.replace(String.to_multibyte(widechar, dst_int))
    @encoding = dst
    return self
  end
  
  #--------------------------------------------------------------------------
  UTF8_CAP = {"À"=>"à","Á"=>"á","Â"=>"â","Ä"=>"ä","Å"=>"å","Æ"=>"æ","Ç"=>"ç",
     "È"=>"è","É"=>"é","Ê"=>"ê","Ë"=>"ë","Ì"=>"ì","Î"=>"î","Ï"=>"ï","Ð"=>"ð",
     "Ñ"=>"ñ","Ò"=>"ò","Ó"=>"ó","Ô"=>"ô","Õ"=>"õ","Ö"=>"ö","Ø"=>"ø","Ù"=>"ù",
     "Ú"=>"ú","Û"=>"û","Ü"=>"ü","Ý"=>"ý","Þ"=>"þ"}
  #--------------------------------------------------------------------------
  UTF8_PLAIN = {"À"=>"A","Á"=>"A","Â"=>"A","Ä"=>"A","Å"=>"A","Æ"=>"A",
     "Ç"=>"C","È"=>"E","É"=>"E","Ê"=>"E","Ë"=>"E","Ì"=>"I","Î"=>"I","Ï"=>"I",
     "Ð"=>"D","Ñ"=>"N","Ò"=>"O","Ó"=>"O","Ô"=>"O","Õ"=>"O","Ö"=>"O","Ø"=>"O",
     "Ù"=>"U","Ú"=>"U","Û"=>"U","Ü"=>"U","Ý"=>"Y","à"=>"a","á"=>"a","â"=>"a",
     "ä"=>"a","å"=>"a","æ"=>"a","ç"=>"c","è"=>"e","é"=>"e","ê"=>"e","ë"=>"e",
     "ì"=>"i","î"=>"i","ï"=>"i","ð"=>"d","ñ"=>"n","ò"=>"o","ó"=>"o","ô"=>"o",
     "õ"=>"o","ö"=>"o","ø"=>"o","ù"=>"u","ú"=>"u","û"=>"u","ü"=>"u","ý"=>"y"}
  #--------------------------------------------------------------------------
  
  #--------------------------------------------------------------------------
  # * bytes
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-bytes
  #--------------------------------------------------------------------------
  def bytes
    array = []
    self.each_byte{|x| array.push(x)}
    return array
  end
  #--------------------------------------------------------------------------
  # * chars
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-chars
  #--------------------------------------------------------------------------
  def chars
    return self.split(//)
  end
  #--------------------------------------------------------------------------
  # * ascii_only?
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-ascii_only-3F
  #--------------------------------------------------------------------------
  def ascii_only?
    return false if self.chars.size != self.bytes.size
    return false if self.bytes.any? {|x| x >= 128}
    return true
  end
  #--------------------------------------------------------------------------
  # * bytesize
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-bytesize
  #--------------------------------------------------------------------------
  def bytesize
    if String.method_defined?(:bytes)
      return self.bytes.size
    else
      return self.size
    end
  end
  #--------------------------------------------------------------------------
  # * charsize
  #--------------------------------------------------------------------------
  # (Método propio)
  #--------------------------------------------------------------------------
  def charsize
    return self.chars.size
  end
  #--------------------------------------------------------------------------
  alias_method(:byteslice, :slice)
  #--------------------------------------------------------------------------
  # * charslice(index)
  # * charslice(start, length)
  # * charslice(range)
  #--------------------------------------------------------------------------
  # (Método propio)
  #--------------------------------------------------------------------------
  def charslice(*args)
    self.chars.slice(*args).to_s
  end
  #--------------------------------------------------------------------------
  # * charslice!(index)
  # * charslice!(start, length)
  # * charslice!(range)
  #--------------------------------------------------------------------------
  # (Método propio)
  #--------------------------------------------------------------------------
  def charslice!(*args)
    result = self.charslice(*args)
    return nil if self == result
    self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * charindex(index)
  #--------------------------------------------------------------------------
  # (Método propio)
  #--------------------------------------------------------------------------
  def charindex(index)
    result = 0 ; chars = self.chars
    for i in 0...index
      result += chars[i].bytesize
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * codepoints
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-codepoints
  #--------------------------------------------------------------------------
  def codepoints
    result = [] ; chars = self.chars
    for i in 0...chars.size
      str = "" ; b = chars[i].bytes
      case b.size
      when 1
        u = b[0]
      when 2
        u = (b[0]-192)*64 + b[1]-128
      when 3
        u = (b[0]-224)*4096 + (b[1]-128)*64 + b[2]-128
      when 4
        u = (b[0]-240)*262144 + (b[1]-128)*4096 + (b[2]-128)*64 + b[3]-128
      end
      result.push(u)
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * downcase | downcase(:ascii)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-downcase
  #--------------------------------------------------------------------------
  alias downcase_ascii downcase unless $@
  def downcase(type=nil)
    return downcase_ascii if type == :ascii || self.encoding != "UTF-8"
    result = self.downcase_ascii
    for i in 0...result.chars.size
      index = self.charindex(i)
      size = result.chars[i].bytesize
      chr = result[index, size]
      if UTF8_CAP.keys.include?(chr)
        result[index, size] = UTF8_CAP[chr]
      end
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * downcase! | downcase!(:ascii)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-downcase
  #--------------------------------------------------------------------------
  alias downcase_ascii! downcase! unless $@
  def downcase!(type=nil)
    result = self.downcase(type)
    return nil if self == result
    self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * upcase | upcase(:ascii)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-upcase
  #--------------------------------------------------------------------------
  alias upcase_ascii upcase unless $@
  def upcase(type=nil)
    return upcase_ascii if type == :ascii || self.encoding != "UTF-8"
    result = self.upcase_ascii
    for i in 0...result.chars.size
      index = self.charindex(i)
      size = result.chars[i].bytesize
      chr = result[index, size]
      if UTF8_CAP.values.include?(chr)
        result[index, size] = UTF8_CAP.invert[chr]
      end
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * upcase! | upcase!(:ascii)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-upcase
  #--------------------------------------------------------------------------
  alias upcase_ascii! upcase! unless $@
  def upcase!(type=nil)
    result = self.upcase(type)
    return nil if self == result
    self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * capitalize | capitalize(:ascii)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-capitalize
  #--------------------------------------------------------------------------
  alias capitalize_ascii capitalize unless $@
  def capitalize(type=nil)
    return capitalize_ascii if type == :ascii || self.encoding != "UTF-8"
    result = self.capitalize_ascii
    for i in 0...result.chars.size
      index = self.charindex(i)
      size = result.chars[i].bytesize
      chr = result[index, size]
      k = (i == 0) ? UTF8_CAP.values : UTF8_CAP.keys
      if k.include?(chr)
        if i == 0
          result[index, size] = UTF8_CAP.invert[chr]
        else
          result[index, size] = UTF8_CAP[chr]
        end
      end
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * capitalize! | capitalize!(:ascii)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-capitalize
  #--------------------------------------------------------------------------
  alias capitalize_ascii! capitalize! unless $@
  def capitalize!(type=nil)
    result = self.capitalize(type)
    return nil if self == result
    self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * swapcase | swapcase(:ascii)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-swapcase
  #--------------------------------------------------------------------------
  alias swapcase_ascii swapcase unless $@
  def swapcase(type=nil)
    return swapcase_ascii if type == :ascii || self.encoding != "UTF-8"
    result = self.swapcase_ascii
    for i in 0...result.chars.size
      index = self.charindex(i)
      size = result.chars[i].bytesize
      chr = result[index, size]
      if UTF8_CAP.values.include?(chr)
        result[index, size] = UTF8_CAP.invert[chr]
      elsif UTF8_CAP.keys.include?(chr)
        result[index, size] = UTF8_CAP[chr]
      end
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * swapcase! | swapcase!(:ascii)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-swapcase
  #--------------------------------------------------------------------------
  alias swapcase_ascii! swapcase! unless $@
  def swapcase!(type=nil)
    result = self.swapcase(type)
    return nil if self == result
    self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * each_char {|str| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-each_char
  #--------------------------------------------------------------------------
  def each_char(&block)
    self.chars.each(&block)
  end
  #--------------------------------------------------------------------------
  # * each_codepoint {|integer| block }
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-each_codepoint
  #--------------------------------------------------------------------------
  def each_codepoint(&block)
    self.codepoints.each(&block)
  end
  #--------------------------------------------------------------------------
  # * lines
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-lines
  #--------------------------------------------------------------------------
  def lines
    result = []
    self.each_line {|line| result.push(line)}
    return result
  end
  #--------------------------------------------------------------------------
  # * getbyte(index)
  #--------------------------------------------------------------------------
  def getbyte(index)
    return self.bytes[index]
  end
  #--------------------------------------------------------------------------
  # * setbyte(index)
  #--------------------------------------------------------------------------
  def setbyte(index, int)
    self[index] = int
    return self
  end
  #--------------------------------------------------------------------------
  # * b
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-b
  #--------------------------------------------------------------------------
  def b
    result = self.clone
    result.encode!("OEM")
    return result
  end
  #--------------------------------------------------------------------------
  # * ord
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-ord
  #--------------------------------------------------------------------------
  def ord
    return self.codepoints[0]
  end
  #--------------------------------------------------------------------------
  # * reverse
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-reverse
  #--------------------------------------------------------------------------
  alias reverse_ascii reverse unless $@
  def reverse
    return reverse_ascii if self.encoding != "UTF-8"
    result = "" ; chars = self.chars.reverse
    for i in 0...chars.size
      result.concat(chars[i])
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * reverse!
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-reverse
  #--------------------------------------------------------------------------
  def reverse!
    return self.replace(self.reverse)
  end
  #--------------------------------------------------------------------------
  # * chr
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-chr
  #--------------------------------------------------------------------------
  def chr
    return self.chars[0]
  end
  #--------------------------------------------------------------------------
  # * plain
  #--------------------------------------------------------------------------
  # (Método propio)
  #--------------------------------------------------------------------------
  def plain
    return self if self.encoding != "UTF-8"
    result = "" ; chars = self.chars
    for i in 0...chars.size
      index = self.charindex(i)
      size = chars[i].bytesize
      if size > 1
        if UTF8_PLAIN.keys.include?(chars[i])
          result.concat(UTF8_PLAIN[chars[i]])
        end
      else
        result.concat(chars[i])
      end
    end
    return result
  end
  #--------------------------------------------------------------------------
  # * plain!
  #--------------------------------------------------------------------------
  # (Método propio)
  #--------------------------------------------------------------------------
  def plain!
    result = self.plain
    return nil if self == result
    self.replace(result)
  end
  #--------------------------------------------------------------------------
  # * valid_char?
  #--------------------------------------------------------------------------
  # (Método propio)
  #--------------------------------------------------------------------------
  def valid_char?
    chars = self.chars
    for i in 0...chars.size
      chr = chars[i]
      if chr.dump.include?("\\")
        bytes = chr.bytes
        next if bytes.size == 1 && bytes[0] < 128
        return false if chr.unpack("S*").size == 0
      end
    end
    return true
  end
  #--------------------------------------------------------------------------
  # * valid_encoding?
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-valid_encoding-3F
  #--------------------------------------------------------------------------
  def valid_encoding?
    return self.chars.all?{|chr| chr.valid_char?}
  end
  #--------------------------------------------------------------------------
  # * chop
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-chop
  #--------------------------------------------------------------------------
  def chop
    return self[0...self.size-2] if self[self.size - 2...self.size] == "\r\n"
    chars = self.chars
    return chars[0...chars.size-1].join
  end
  #--------------------------------------------------------------------------
  # * chop!
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-chop
  #--------------------------------------------------------------------------
  def chop!
    return nil if self.empty?
    self.replace(self.chop)
    return self
  end
  #--------------------------------------------------------------------------
  # * partition(sep)
  # * partition(regexp)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-partition
  #--------------------------------------------------------------------------
  alias partition_str partition unless $@
  def partition(sep=nil, &block)
    return partition_str(&block) if sep.nil?
    i = self.index(sep)
    return [self, "", ""] if i.nil?
    s = self.scan(sep)[0].size
    return [self[0...i], self[i...(i+s)], self[(i+s)...self.size]]
  end
  #--------------------------------------------------------------------------
  # * rpartition(sep)
  # * rpartition(regexp)
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-rpartition
  #--------------------------------------------------------------------------
  def rpartition(sep)
    i = self.rindex(sep)
    return ["", "", self] if i.nil?
    s = self.scan(sep)[-1].size
    return [self[0...i], self[i...(i+s)], self[(i+s)...self.size]]
  end
  #--------------------------------------------------------------------------
  # * undump
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-undump
  #--------------------------------------------------------------------------
  def undump
    return eval(self).to_s
  end
  #--------------------------------------------------------------------------
  # * sum
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-sum
  #--------------------------------------------------------------------------
  def sum
    result = 0
    self.each_byte {|x| result += x }
    return result
  end
  #--------------------------------------------------------------------------
  # * scrub
  # * scrub(repl)
  # * scrub{|bytes|}
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-scrub
  #--------------------------------------------------------------------------
  def scrub(rep="", &block)
    result = [] ; chars = self.chars
    for i in 0...chars.size
      chr = chars[i]
      if chr.valid_char?
        result.push(chr)
      else
        if block_given?
          result.push(yield chr)
        else
          result.push(rep)
        end
      end
    end
    return result.join
  end
  #--------------------------------------------------------------------------
  # * scrub!
  # * scrub!(repl)
  # * scrub!{|bytes|}
  #--------------------------------------------------------------------------
  # https://ruby-doc.org/core-2.5.0/String.html#method-i-scrub
  #--------------------------------------------------------------------------
  def scrub!(rep="", &block)
    return self.replace(self.scrub)
  end
end

#==============================================================================
# * Symbol
#==============================================================================

class Symbol
  def [](*args)         return self.to_s[*args]                 end
  def =~(other)         return self.to_s =~ other               end
  def capitalize(*args) return self.to_s.capitalize(*args)      end
  def downcase(*args)   return self.to_s.downcase(*args)        end
  def swapcase(*args)   return self.to_s.swapcase(*args)        end
  def upcase(*args)     return self.to_s.upcase(*args)          end
  def casecmp(other)    return self.to_s.casecmp(other.to_s)    end
  def casecmp?(other)   return self.to_s.casecmp?(other.to_s)   end
  def empty?()          return self.to_s.empty?                 end
  def match(*args)      return self.to_s.match(*args)           end
  def match?(*args)     return self.to_s.match?(*args)          end
  def succ()            return self.to_s.succ.intern            end
  def size()            return self.to_s.size                   end
  def slice(*args)      return self.to_s[*args]                 end
  def to_proc()         return Proc.new {|x| x.send(self) }     end
end

Cada vez sé menos qué queda pero supongo que pronto subiré alguno más xD

Para quien aún quiera más métodos adicionales similares a los que he subido, aquí hay una buena colección:
Rubyworks - Facets
Y aquí también hay alguno más, aunque muchas cosas no sirven en RPG maker:
Ruby examples (khusnetdinov)
Y si queréis algunos trucos sobre rendimiento, mirad ésta colección:
Best Ruby Tricks (franzejr)

Intentaré buscar alguna colección más.
avatar
Wecoc
Administrador
Administrador



Créditos 12291

Gracias : 646

Volver arriba Ir abajo

RPG Maker XP Re: [XP] Colección de Snippets para RPG maker

Mensaje por Eron el 2018-01-26, 13:55

Parece mentira que eso de Array+ siga activo, Wecoc... Lo de juntar varios snippets en un topic está bien, ya saqué alguna cosa de esa lista que has puesto en el primer post.
Te he buscado y arreglado algunos snippets de esos, aunque... son poco habituales x'D Puedes añadirlos donde quieras o "pulirlos" o lo que sea, aunque creo que el topic este es para que los dejemos cada uno a nuestro aire.

1) Object con opción metaclass (definir métodos externamente)
Adaptado de un autor desconocido. No requiere créditos.

Código:
class Object
  def metaclass
    class << self
      self
    end
  end
  
  def meta_eval(&blk)
    metaclass.instance_eval(&blk)
  end
  def meta_def(name, &blk)
    meta_eval { define_method(name, &blk) }
  end
  def class_def(name, &blk)
    class_eval { define_method(name, &blk) }
  end
  
  define_method :not do
    Not.new(self)
  end

  class Not
    private *instance_methods.select { |m| m !~ /(^__|^\W|^binding$)/ }
    def initialize(subject)
      @subject = subject
    end
    def method_missing(sym, *args, &blk)
      !@subject.send(sym, *args, &blk)
    end
  end

  def class_attr_accessor(*attrs)
    metaclass.send(:attr_accessor, *attrs)
  end
end

2) Array
Lo creé yo, no requiere créditos. Parcialmente adaptado del ERON module.

Código:
class Array
  def strip(*args)
    list=[]
    self.each_with_index do | e, i |
      if(not args.member?(i))
        list << e
      end
    end
    return list
  end
  
  def find_index(n)
    find_all_index(n)[0]
  end
  
  def find_all_index(n)
    ind = []
    for i in 0...self.size
      ind.push(i) if self[i] == n
    end
    return ind
  end
  
  def keep_if(&block)
    replace select(&block)
  end

  def sort_by_array(other)
    new_array = []
    self_array = []
    return self if self.size != other.size
    for i in 0...self.size
      self_array.push self[i]
    end
    while other.size > 0
      for i in 0...other.size
        if other[i] == other.min
          min = i
        end
      end
      new_array.push self_array[min]
      other.delete_at(min)
      self_array.delete_at(min)
    end
    return new_array
  end
  
  def sort_by_array!(other)
    self.replace(sort_by_array(other))
  end
  
  # p ["A", "B", "C"].sort_by_array([2, 1, 4])
end

3) Enumerable
Autor: Eron, no requiere créditos.

Código:
module Enumerable
  def size=(value)
    if value < self.size
      self.replace(self.slice(0...value))
    elsif value > self.size
      self.fill(self.size...value){ nil }
    end
    self
  end
  
  def each_with_prev
    last_element = nil
    each do |e|
      yield e, last_element
      last_element = e
    end
  end

  def map_with_index
    result = []
    self.each_with_index do |elt, idx|
      result << yield(elt, idx)
    end
    result
  end
  
  def group_hash
    inject({}) do |groups, element|
      (groups[yield(element)] ||= []) << element
      groups
    end
  end
end

4) Hash
Autor desconocido, y no recuerdo de donde lo saqué, lo he adaptado algo. Uso libre.

Código:
class Hash
  def allow_keys(*keys)
    tmp = self.clone
    tmp.delete_if {|k,v| !keys.include?(k) }
    tmp
  end
  
  def allow_keys!(*keys)
    delete_if{|k,v| !keys.include?(k) }
  end
  
  def deny_keys(*keys)
    tmp = self.clone
    tmp.delete_if {|k,v| keys.include?(k) }
    tmp
  end
  
  def deny_keys!(*keys)
    delete_if {|k,v| keys.include?(k) }
  end
  
  def allow_values(*values)
    tmp = self.clone
    tmp.delete_if {|k,v| !values.include?(k) }
    tmp
  end
  
  def allow_values!(*values)
    delete_if {|k,v| !values.include?(k) }
  end
  
  def deny_values(*values)
    tmp = self.clone
    tmp.delete_if {|k,v| values.include?(k) }
    tmp
  end
  
  def deny_values!(*values)
    delete_if {|k,v| values.include?(k) }
  end
end

5) Symbol to_proc con varios argumentos
Autor: Eron, no requiere créditos.

Código:
class Symbol
  def to_proc
    proc { |*args| args.shift.send(self, *args) }
  end
end

Puedo buscar más.
avatar
Eron
Principiante
Principiante

0/3

Créditos 3599

Gracias : 60

Volver arriba Ir abajo

RPG Maker XP Re: [XP] Colección de Snippets para RPG maker

Mensaje por Wecoc el 2018-01-28, 19:28

@Eron Gracias por esos aportes, por lo que veo son añadidos algo especiales. No entiendo para qué sirve el primero ni cómo usarlo exactamente. Los demás los probé y van bien, pueden ser útiles en algún caso. Te recomendaría poner ejemplos o al menos un comentario de qué hace cada método tal como yo he ido haciendo, porque si no es fácil perderse con éste tipo de snippets. Ah, y si puedes aportar más te lo agradeceré, ya te he dado un Gracias ;)

He subido una nueva versión del Regexp (rb2RGSS), ahora es la 1.2. Sigue sin tener todas las funciones que tiene Ruby 2.5, pero las que faltan la mayoría están relacionadas con los Unicode así que sería más un problema con la clase String. En un futuro puede que haga otra parte solo para dar mejor soporte de ese tipo.
avatar
Wecoc
Administrador
Administrador



Créditos 12291

Gracias : 646

Volver arriba Ir abajo

RPG Maker XP Re: [XP] Colección de Snippets para RPG maker

Mensaje por Contenido patrocinado


Contenido patrocinado


Volver arriba Ir abajo

Ver el tema anterior Ver el tema siguiente Volver arriba


Permisos de este foro:
No puedes responder a temas en este foro.