¿Hay un opuesto de incluir? para Ruby Matrices?


Tengo la siguiente lógica en mi código:

if [email protected]?(p.name) do
  ...
end

@players es una matriz. ¿Hay un método para que pueda evitar el !?

Idealmente, este fragmento sería:

if @players.does_not_include?(p.name)  do
  ...
end
Author: the Tin Man, 2012-04-27

11 answers

if @players.exclude?(p.name) do
    ...
end

ActiveSupport añade el método exclude? tanto a Array como a String. Esto no es Rubí puro, pero es utilizado por muchos rubistas.

 281
Author: dizzy42,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-31 10:06:29

Aquí tienes:

unless @players.include?(p.name)
  ...
end

Puede echar un vistazo a la Guía de estilo de Ruby para obtener más información sobre técnicas similares.

 78
Author: Bozhidar Batsov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-16 06:20:51

Qué tal lo siguiente:

unless @players.include?(p.name)
  ....
end
 10
Author: ilasno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-25 02:25:13
module Enumerable
  def does_not_include?(item)
    !include?(item)
  end
end

Ok, pero en serio, el menos funciona bien.

 5
Author: Jesse Wolgamott,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-27 17:56:38

Mirando solo a Ruby

TL; DR

Use none? pasándole un bloque usando == para la comparación:

[1, 2].include?(1)
  #=> true
[1, 2].none? { |n| 1 == n  }
  #=> false

Array # include?

Array#include? acepta un argumento y usa == para verificar con cada elemento en el array:

player = [1, 2, 3]
player.include?(1)
 #=> true

Enumerable # none?

Enumerable#none? también puede aceptar un argumento en cuyo caso se utiliza === para la comparación. Para obtener el comportamiento opuesto a include? omitimos el parámetro y le pasamos un bloque usando == para la comparación.

player.none? { |n| 7 == n }
 #=> true 
!player.include?(7)    #notice the '!'
 #=> true

Puntos a considerar

En el ejemplo anterior podemos usar:

player.none?(7)
 #=> true

Eso es porque Integer#== y Integer#=== son equivalentes. Pero considere:

player.include?(Integer)
 #=> false
player.none?(Integer)
 #=> false

none? devuelve false porque Integer === 1 #=> true. Pero realmente un método legítimo notinclude? debe devolver true. Así como lo hicimos antes:

player.none? { |e| Integer == e  }
 #=> true
 3
Author: Sagar Pandya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-25 07:53:36

Utilizar a menos que.

unless @players.include?(p.name) do
  ...
end
 1
Author: Nikita Beloglazov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-27 17:55:03

Usar unless está bien para sentencias con cláusulas simples include? pero, por ejemplo, cuando necesita verificar la inclusión de algo en una Array pero no en otra, el uso de include? con exclude? es mucho más amigable.

if @players.include? && @spectators.exclude? do
  ....
end

Pero como dizzy42 dice anteriormente, el uso de exclude? requiere ActiveSupport

 0
Author: MeWillWork4Food,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-27 10:35:36

Intenta algo como esto:

@players.include?(p.name) ? false : true
 0
Author: ckshei,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-03 20:59:24

Prueba esto, es Rubí puro así que no hay necesidad de añadir ningún framework periférico

if @players.include?(p.name) == false do 
  ...
end

Estuve luchando con una lógica similar durante unos días, y después de revisar varios foros y paneles de preguntas y respuestas para poco provecho, resultó que la solución era en realidad bastante simple.

 0
Author: KarmaDeli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-10 17:18:32

Estaba buscando esto por mí mismo, encontré esto, y luego una solución. La gente está usando métodos confusos y algunos métodos que no funcionan en ciertas situaciones o no funcionan en absoluto.

Sé que es demasiado tarde ahora, teniendo en cuenta que esto se publicó hace 6 años, pero espero que los futuros visitantes encuentren esto (y espero que pueda limpiar su código y el suyo).)

Solución simple:

if not @players.include?(p.name) do
  ....
end
 0
Author: Voidableryzer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-24 18:56:50

Puede usar

unless @players.include?(p.name) do
...
end

A menos que sea opuesto al si.

O puede usar rechazar puede rechazar los elementos no requeridos

@players.reject{|x| x==p.name}

Después de obtener los resultados, puede hacer su implementación

 0
Author: tekuri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-12 04:02:39