include? 메서드
Coddy Ruby 여정의 기초 섹션에 포함된 레슨 — 88개 중 72번째.
배열을 다룰 때, 특정 작업을 수행하기 전에 특정 요소가 존재하는지 확인해야 하는 경우가 많습니다. Ruby의 include? 메서드는 이 질문에 직접적으로 답하며, true 또는 false를 반환합니다.
fruits = ["apple", "banana", "orange"]
puts fruits.include?("banana") # 출력: true
puts fruits.include?("grape") # 출력: false이 메서드는 정확한 일치 여부를 확인하므로, 문자열의 대소문자를 구분합니다:
colors = ["Red", "Green", "Blue"]
puts colors.include?("Red") # 출력: true
puts colors.include?("red") # 출력: false이 메서드는 조건문에서 특히 유용합니다. 배열을 루프하며 요소를 찾는 대신, 단순히 해당 요소가 있는지 물어볼 수 있습니다:
allowed_users = ["alice", "bob", "charlie"]
current_user = "bob"
if allowed_users.include?(current_user)
puts "Access granted"
else
puts "Access denied"
endinclude? 메서드는 숫자, 심볼, 심지어 다른 배열을 포함하여 배열에 저장된 모든 데이터 타입에 대해 작동합니다.
챌린지
쉬움두 줄의 입력을 읽으십시오:
- 상점에서 판매 가능한 품목 목록, 쉼표로 구분된 문자열 (예:
apple,banana,orange,milk,bread) - 쇼핑 리스트에 있는 품목 목록, 쉼표로 구분된 문자열 (예:
banana,eggs,milk,cheese)
쇼핑 리스트의 각 품목에 대해, include? 메서드를 사용하여 상점에서 판매 가능한지 확인하십시오. 각 품목 뒤에 상점 재고에 있는지 여부에 따라 Available 또는 Not available을 출력하십시오.
include?는 정확히 일치하는지 확인하므로, 비교 시 대소문자를 구분한다는 점에 유의하십시오.
예를 들어, 입력이 apple,banana,orange,milk,bread와 banana,eggs,milk,cheese인 경우, 출력은 다음과 같아야 합니다:
banana - Available
eggs - Not available
milk - Available
cheese - Not available입력이 Red,Green,Blue와 red,Green,Yellow인 경우, 출력은 다음과 같아야 합니다:
red - Not available
Green - Available
Yellow - Not available입력이 coffee,tea,juice와 coffee,water,tea인 경우, 출력은 다음과 같아야 합니다:
coffee - Available
water - Not available
tea - Available입력이 pen,pencil,eraser와 pen인 경우, 출력은 다음과 같아야 합니다:
pen - Available치트 시트
include? 메서드는 배열에 특정 요소가 존재하는지 확인하여 true 또는 false를 반환합니다:
fruits = ["apple", "banana", "orange"]
puts fruits.include?("banana") # 출력: true
puts fruits.include?("grape") # 출력: false이 메서드는 정확한 일치를 수행하며 문자열의 대소문자를 구분합니다:
colors = ["Red", "Green", "Blue"]
puts colors.include?("Red") # 출력: true
puts colors.include?("red") # 출력: false조건문에서 include?를 사용하여 요소의 존재 여부를 확인할 수 있습니다:
allowed_users = ["alice", "bob", "charlie"]
current_user = "bob"
if allowed_users.include?(current_user)
puts "Access granted"
else
puts "Access denied"
endinclude? 메서드는 숫자, 심볼, 배열을 포함한 모든 데이터 타입에서 작동합니다.
직접 해보기
# 상점 재고 읽기 (쉼표로 구분된 항목들)
store_items = gets.chomp.split(",")
# 쇼핑 목록 읽기 (쉼표로 구분된 항목들)
shopping_list = gets.chomp.split(",")
# TODO: 아래에 코드를 작성하세요
# 쇼핑 목록의 각 항목에 대해, include? 메서드를 사용하여
# 상점에 해당 항목이 있는지 확인하고 결과를 출력하세요이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.